[Rd] Good practice for naming classes, builders, attributes, getters/setters for object composition

Julien Idé julien.ide.fr at gmail.com
Fri Nov 20 09:39:52 CET 2015


Hey everyone,

I am developing a package and I am wondering if there is a good practice
for naming classes, builders, attributes getters and setters when dealing
with object composition. I know that it is usually a good practice to give
to the builder the same name as the class and, if possible, to avoid to use
upper case letters. My problem is that, when I build an object containing
an other object (of an other class), at the end my getters can have the
same name as my builders. Here is an example.

Lets define a first class "bonds" to store atomic bonds information:
bonds <- function(ind1, ind2, order){
  obj <- data.frame(ind1 = ind1, ind2 = ind2, order = order)
  class(obj) <- c("bonds", class(obj))
  return(obj)
}

Now I when to define an other class to store atomic properties.
As atoms can be bonded to each other, I add a "bonds" attribute which is of
class "bonds".
atoms <- function(symb, mass, charge, bonds){
  obj <- data.frame(symb = symb, mass = mass, charge = charge)
  attr(obj, "bonds") <- bonds
  class(obj) <- c("atoms", class(obj))
  return(obj)
}
Now if I when to get the "bonds" attribute of an "atoms" object, I have to
define:
bonds <- function(x)
  UseMethod("bonds")

bonds.atoms <- function(x)
  attr(x, "bonds")

As you can see my getter has the same name as the builder for class "bonds".
Any suggestion?

	[[alternative HTML version deleted]]



More information about the R-devel mailing list