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

Michael Lawrence lawrence.michael at gene.com
Fri Nov 20 13:48:55 CET 2015


On Fri, Nov 20, 2015 at 12:39 AM, Julien Idé <julien.ide.fr at gmail.com> wrote:
> 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?
>

I would definitely distinguish constructors from accessors somehow. In
Bioconductor, we use capitalized class names, and thus capitalized
constructors. If you don't like capital letters, you will need to
think of something else ;) Like new_bonds(), get_bonds(), etc.

Btw, bonds are not intrinsic to atoms, but rather molecules. You
should consider a molecule class.

>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list