[R] initalizing and checking validity of S4 classes

Seth Falcon sfalcon at fhcrc.org
Wed Jul 25 19:21:53 CEST 2007


Martin Morgan <mtmorgan at fhcrc.org> writes:

> Hi Michal --
>
> Add validObject to your initialize method:

Actually, a call to valid object is part of the default initialization
method which has been masked.  A different solution, which might have
some other benefits is to delegate back to the default method using
callNextMethod.  So you could do:

setMethod("initialize", "someclass",
function(.Object, v=numeric(0), l=character(0))
{
    # strip the vector names

    cv <- v
    cl <- l
    names(cv) <- NULL
    names(cl) <- NULL
    callNextMethod(.Object=.Object, v=cv, l=cl)
} )


> Here are two interpretations of this. (1) using 'initialize' means
> that you are taking control of the initialization process, and hence
> know when you need to call validObject.

Yes.  Anytime you specialize a method you must take responsibility for
any less specific methods.  In this case, the default 'initialize'
does object validation.  So if you want validation, you either need to
do it directly or invoke the default method.

> (2) Responsibility for object
> validity is ambiguous -- does it belong with 'new', 'initialize', or a
> 'constructor' that the programmer might write? This is particularly
> problematic with R's copy semantics, where creating transiently
> invalid objects seems to be almost necessary (e.g., callNextMethod()
> in 'initialize' might initialize the inherited slots of the object,
> but the object itself is of the derived class and could well be
> invalid 'invalid' after the base class has finished with initialize).

This is a good point.  It suggests that, at least, one must initialize
all non-inherited slots to valid values _before_ calling the next
method.

+ seth

-- 
Seth Falcon | Computational Biology | Fred Hutchinson Cancer Research Center
http://bioconductor.org



More information about the R-help mailing list