%\VignetteIndexEntry{S4 - Composition vs Inheritance and the package msbase}
%\VignetteDepends{}
%\VignetteKeywords{Mass Spectrometry}
%\VignettePackage{msbase} 
\documentclass[a4paper]{article}

\title{S4 - Composition vs Inheritance and the package msbase}
\author{Witold Eryk Wolski}

\begin{document}

\maketitle

\setkeys{Gin}{width=0.6\textwidth}

\section*{Introduction}

In the package \emph{msbase} \emph{inheritance} was used to extend the \texttt{list} class functionality as opposed to the package \emph{biobase}\cite{BIOC} where \emph{composition} was used to the same purpose. I describe here the programming techniques used while implementing the functionality of the package \emph{msbase}.
Object composition and inheritance are two techniques for reusing functionality in object-oriented systems. The choice between the \emph{composition} (``has a'') relation and the \emph{inheritance} (``is a'') relation is a frequent one if we use programming languages with type checking and OOP features. It is a sensible one, because the consequences of this choice are not readily visible. We show various ways how the ``is a'' and ``has a'' relation can be expressed in \texttt{S4} \cite{Chambers1998} and explain it using the old style \texttt{R} \texttt{list} as parent class because there are some differences compared with extending \texttt{S4} classes. 

\section*{Nomenclature}

 %``When a subclass inherits from a parent class, it includes the definitions of all the data and operations that the parent class defines'' \cite{Gamma93}. 

In \texttt{S4} the \texttt{contains} keyword in the \texttt{setClass} function is used to express object {\em inheritance}\cite{Gamma93,Rajlich98}.  It means that all methods and \emph{slots} defined for the parent class are also valid for the inheriting subclass. Because the parent class implementation is visible to the subclasses this type of reuse is also called {\bf white-box} reuse. Inherited classes can be assigned to slots and function arguments of the parent class type. The arguments and slots of the parent class type are \emph{polymorphic}.

 Object {\em composition}\cite{Gamma93} is expressed in S4 by the keyword \texttt{representation} in \texttt{setClass}. The methods and slots of a class stored in a slot can not be accessed directly, {\em e.g}  to access the the object it must be dereferenced. The internals of the composed objects are unknown. Because objects are treated as "black boxes," this type of reuse is often called {\bf black-box} reuse \cite{Rajlich98}.

In the sample code we label classes defined using inheritance with a leading upper \texttt{I} and classes definied using composition with a upper leading \texttt{C}. Slot names start always with a lower letter.

\section*{Motivation} 
% The outcome of a mass spectrometric measurement and of spectra processing is an list of mass, intensity value pairs which can be stored in a matrix. During one experiment several hundred samples are measured generating a result set of mass lists of different lengths. To this set of data different calibration and filtering functions are applied afterwards.

The \texttt{base:list} class is one of the generic classes in \texttt{R}. It can store objects of any class and it provides a huge amount of functionality e.g \texttt{unlist, lapply, sapply, do.call} etcetera. Here we provide examples how to specialize the \texttt{list} class. {\em e.g.} how to implement a list with an additional \texttt{slotA} field to store e.g. some additional information. From the OO design point of view this is clearly(?) a is a \texttt{list} with \texttt{slotA} slot\footnote{An example how to to provide type checking of list content can be found at the S Programming Workshop page \cite{SWorkshop}}.

\section*{The Inheritance Relation}

The \emph{inheritance} relation in S4 can be defined in various ways \cite{Chambers1998}. Either the parent class is passed as not named argument to the \texttt{representation} function or as the argument to the \texttt{contains} keyword in the class definition  \emph{e.g:} 

<<EXTENDSRELATION,eval=TRUE>>=
setClass("Ia",representation("list",names="character",slotA="character"))
setClass(
         "Ia"
         ,contains="list"
         ,representation(
                         names="character"
                         ,slotA="character"
                        )
         ,prototype(slotA="content")
         )
getClass("Ia")
@

These declarations are synonymous. I prefer the second definition because the additional keyword \texttt{contains} emphasises that inheritance is different than composition. The class definition is printed by the function \texttt{getClass}. Note that the class \texttt{Ia} has an additional slot \texttt{.Data} which was generated automatically. This slot keeps the parent class. 

Normally if inheriting, all slots of the parent class are present in the child class. The \texttt{R} \texttt{list} is a \emph{thingy} from pre-class times, and has no class definition\footnote{To ``Register an old-style (a.k.a. `S3') class as a formally defined
     class'' the function \texttt{setOldClass} is used. All old-style classes in the base and recomended packages are already registered.}. Hence, an object inheriting from a \texttt{list} does not have it automatically,  and if we want that the inheriting class has names, we have to define a slot \texttt{names} ourselves. By our definition the type of the names is limited to \texttt{character} which may be of advantage on the ``C side'' of the object. %By \texttt{object@names} the \texttt{list} attribute names can be accessed.

By the \texttt{new} function a instance of a class is created.  There are several ways to intitialize an object:
The first is to provide all the data to the \texttt{new} function, {\em e.g.}
<<>>=
xx<-as.list(1:4)
names(xx)<-letters[1:4]
ea <- new("Ia",xx,slotA="my first S4 class")
@ 


We can aslo assign the data afterwards using \texttt{@} to access the slots. To assign an object of the \texttt{list} class to the \texttt{Ia} class we are either use the function \texttt{as}. There is a default \texttt{as} function provided to \emph{cast} objects of the parent class into an object of the inheriting class. 

<<INit,eval=TRUE>>=
ia <- new("Ia")
ia@slotA<-"my first S4 class"
as(ia,"list")<-xx
@ 
An alternative way to assign the data is to access the \texttt{.Data} slot directly. 

<<ASSIGN DIRECTLY>>=
ia@.Data <- xx
@ 

 Note that the names slot was updated automatically to match the content of the \texttt{names} attribute of the \texttt{list}. This update is done by the \texttt{.mergeAttrs} function which is called every time when assigning an object to the \texttt{.Data} slot. The function \texttt{.mergeAttrs} is \emph{exporting} all slots of the parent class.

<<>>=
ia@names
@

\section*{Object composition}

A class definition with member variables only, gives the objects of that class full control over all objects in its slots. By \emph{composition} practically an unlimited number of different classes can be composed within the new class. It means that if calling a function with an object of this class as argument only a function with this class in the signature can be executed. In case of {\em inheritance} method dispatching can occur, this means that if there are no function with an argument of this class a function with an argument of the parent class is executed. The consequence is that if we like to export all of the functionality of the classes stored in member variables we must either reimplement them in the objects interface or dereference the object.

The class \texttt{Ca} is composed of two member variables of class \texttt{list} and \texttt{character}. To be able to call the function \texttt{apply} on the member variable \texttt{list} we implement the method \texttt{lapply}.
  
<<CONTAINSRELATION,eval=TRUE>>=
library(methods)
setClass(
         "Ca"
         ,representation(list="list"
                         ,slotA="character")
         ,prototype(slotA="hello")
         )

setMethod("lapply",signature(X="Ca")
          ,def=function(X,FUN,...)
          {
            X@list <- lapply(X@list,FUN,...)
            return(X)
          }
          )

ca<-new("Ca")
ca@list<-xx

@

Note that the function definition of \texttt{lapply} must have the same signature (argument names) as the function \texttt{lapply} in the package \texttt{base} being the template for the generic. For the \texttt{Ca} class an  \emph{as list} function can be defined using \texttt{setAs}.

<<SETAS,eval=TRUE>>=
setAs("Ca","list"
      ,def=function(from){return(from@list)}
      ,replace=function(from,value){from@list<-value}
      )
@ 

We see that using this design we can provide the same user interface and to this point functionality as by using inheritance. 

\section*{Inherits vs. Compose}

For the \texttt{Ia} class we do not need to provide an implementation of the method \texttt{apply} to be able to call it directly on the object \texttt{ea}.

<<LAPPLY,eval=TRUE>>=
lapply(ca,"^",2)
lapply(ea,"^",2)
@
 
Note that the first call returns an object of class \texttt{Ca} while the second one returns an object of class \texttt{list} since the method \texttt{lapply} of the parent class was executed. If we want a function \texttt{lapply} which returns an object of class \texttt{Ia} we will have equal work to do as for the class \texttt{Ia}.

The examples provided show that using the inheritance relation we need to implement less functions (no implementation of the function \texttt{lapply}, \texttt{as} are necessary). Furthermore, all the \texttt{list} functions will work for the objects of class \texttt{Ca}. The downside of this approach is that good knowledge of the methods provided by the parent classes is required.


The main reason why inheritance was introduced is to allow functions and slots to be \texttt{polymorphic} in type safe programming languages, and not just to make some lines of code superfluous. By \texttt{polymorphism} all inheriting classes can be assigned to a slot or passed to a function defined for the parent class type (polymorphic arguments slots). Composition alone is not able to provide this functionality. Let assume that we have several related classes. The classes \texttt{Ib} and \texttt{Cb} are almost the same as the classes \texttt{Ia,Ca} respectively, except that the \emph{type} of \texttt{slotA} is now \texttt{numeric}.

<<MVCa,eval=TRUE>>=
setClass(
         "Cb"
         ,representation(list="list"
                         ,slotA="numeric"
                         )
         ,prototype(slotA=3)
         )
cb<-new("Cb",list=xx)
setClass(
         "Ib",contains="list"
         ,representation(slotA="numeric")
         )
eb <- new("Ib",xx,slotA = 4)
@ 

If we like to have a function which prints the length of the \texttt{list} for all related classes we can program easily a function \texttt{printlength} with the base class in the signature and it will work for all child classes.

<<Sum,eval=TRUE>>=
setGeneric("printlength",function(object,...) standardGeneric("printlength"))
setMethod("printlength"
          ,signature(object="list")
          ,def=function(object)
          {
            cat("length : ",length(object), " object=",class(object),"\n")
          }
          )
printlength(ea)
printlength(eb)
@ 

It is also easily possible to assign objects of the child class to slots of parent class type.

<<ASSIGN,eval=TRUE>>=
cb.tmp<-cb
cb.tmp@list <- ea
cb.tmp@list <- eb
class(cb.tmp@list)
@

The objects of two different classes can be easily passed to the method defined for the class \texttt{list}.
For composed classes \texttt{S4} provides a different way to have a similar functionality. But they are then either less secure or limited.

\subsection*{Virtual Classes}

\subsubsection*{setClassUnion}

The ``is a'' relation can be defined in \texttt{S4} using the \texttt{setClassUnion}\cite{methods} method. This method defines a new \texttt{virtual} parent class (no instance can be created). For the composed classes \texttt{Ca} and \texttt{Cb} we define a virtual parent class \texttt{VC}. Then we can define a function which has in the function \texttt{signature} an argument of the virtual parent class  \texttt{VC} type. To illustrate the danger inherent in this design we define a third class \texttt{Cc} which does not contain the slot \emph{list} {\em e.g}:

<<PrintlengthC,eval=TRUE>>=
setClass("Cc",representation(slotA="character"))
setClassUnion("VC",c("Ca","Cb","Cc"))
setGeneric("printlengthC",function(object,...) standardGeneric("printlengthC"))
setMethod("printlengthC"
          ,signature(object="VC")
          ,def = function(object)
          {
            cat("length : ",length(object@list), "\n")
          }
          )

printlengthC(ca)
printlengthC(cb)
@ 

The difference between this designs and the inheritance is that by inheritance each function defined for the parent class and working properly with it, will work for the inheriting classes. Hence, defining a class union we must ensure that all classes in the union define a common ``interface'' or implement appropriate checking, otherwise errors at runtime may happen e.g:

<<Error,eval=TRUE>>=
cc<-new("Cc",slotA="hello")
print(try(printlength(cc)))
@

It is also possible to define a slot of the \emph{virtual} class type and assign objects of the inherited classes to it.
<<eval=TRUE>>=
setClass("MC",representation(list="VC"))
mc<-new("MC")
mc@list<-ca
class(mc@list)
mc@list<-cb
class(mc@list)
mc@list<-cc
@ 

\subsubsection*{setIs}

When using \texttt{setClassUnion} we first must define the composed classes and then we can assigned them to an virtual class. If we already have a virtual class and like to set it as a parent class afterward we can use the \texttt{setIs} function \cite{Gentleman03,Chambers1998}. The advantage of defining an virtual class by \texttt{setClass} instead of \texttt{setClassUnion} is that we can define slots that all inheriting classes must define. In the first line of the next example we define a \texttt{virtual} class (by passing the keyword \texttt{"VIRTUAL"} to the class \texttt{representation}). Furthermore we define a slot \texttt{list} of type \texttt{list}.

<<setIS,eval=TRUE>>=
setClass("VC2",representation(list="list"),contains="VIRTUAL")
print(try(new("VC2")))
setIs("Ca","VC2")
print(try(setIs("Cc","VC2")))
setClass("MC",representation(list="VC2"))
mc <- new("MC")
mc@list <- ca
class(mc@list)
@ 


\subsection*{setIs and ``normal'' classes}

 To the \texttt{is} function defined by \texttt{setIs} a \texttt{coerce} and \texttt{replace}  function can be provided. These functions are executed if an object is assigned to a slot or a function argument or a slot of the parent class type.   \texttt{setIs} is still a little buggy when working with old style classes in the current R2.0.0 release. It is not enough to define just the \emph{is} (\texttt{setIs}) relation but we must also define the \emph{as} (\texttt{setAs}) relation.

<<SETIS,eval=TRUE>>=
setIs("Ca","list",coerce=function(obj){return(obj@list)},replace=function(obj,value){obj@list<-value})
#setAs("Ca","list",def=function(from){return(from@list)},replace=function(from,value){from@list<-value})
setIs("Cb","list",coerce=function(obj){return(obj@list)},replace=function(obj,value){obj@list<-value})
setAs("Cb","list",def=function(from){return(from@list)},replace=function(from,value){from@list<-value})
setIs("Cc","list",coerce=function(obj){return(vector("list",0))},replace=function(obj,value){})
setAs("Cc","list",def=function(from){return(vector("list",0))},replace=function(from,value){})
printlength(cb)
printlength(ca)
printlength(cc)
@

By providing a proper definition of the functions \texttt{coerce} and \texttt{replace} using \texttt{setIs} we can ensure for classes that do not have a \texttt{list} slot that a valid object of the {\em base} class is returned. The limitation of \texttt{setIs} is that we are not able to assign to a slot of the parent class type an object of the child class type. At the time of assignment the inheriting class is cast into the parent class.

<<eval=TRUE>>=
cb.tmp@list<-cb
class(cb)
@

\subsection*{Memory}

With respect to memory the extends relation seems to be a little more efficient.

<<MEM,eval=TRUE>>=
object.size(ea)
object.size(ca)
@

\section*{Conclusion}

 By composition we are able to provide a similar user interface as with the extends relation. Hence, the only serious reason for using inheritance is to express the ``is a'' relation to be able to assign objects of different but similar classes to a slot or argument of the parent class type. In addition to inheritance defined in the \texttt{setClass} function by the keyword \texttt{contains}, we can use class unions or the \texttt{setIs} function in \texttt{S4}. The use of virtual classes defined via \texttt{setClassUnion} implies the danger of runtime errors and requires programming discipline.  A safer way to define the ``is a'' relation is to use \texttt{setClass} to define \emph{virtual} classes with slots and \texttt{setIs}. Using the \texttt{coerce} and \texttt{replace} function defined in \texttt{setIs} we can mimic some aspects of object inheritance. Many examples how to combine inheritance and composition to obtain a good design can be found in E. Gammas et al. ``Design Patterns'' \cite{Gamma93}.



% Hence, in cases were we are interested in exporting only a few functions of a class and of no slots it may be much better to use the contains relation.
%Hence, we have to answer only the question which design yields more stable and better maintainable code.  since it is more transparent - we knew to which class the executed method belongs. And we have more control and flexibility - the class can contain an practically unlimited number of other classes. Hence, for providing a specialized version of the \texttt{list} class their are no clear advantages of using any of the designs.

 %To use the extends relation may be better if we provide a just a slight specialization of a super class which already implements a vast of methods, and this methods will retain still fully valid. This is the case for the container classes in the package \texttt{msbase}. Hence, I decided to use the extends relation to implement them. 

\section{Aknowledgments}
Thanks to Mathias Kohl for valuable disussion.


\bibliographystyle{plain}  % Style BST file
  \bibliography{bib} 

\end{document}
