On Mon, Oct 26, 2009 at 11:56 PM, <mtmor...@fhcrc.org> wrote: > Quoting Peng Yu <pengyu...@gmail.com>: > >> I feel tedious when I define a S4 class and the methods. For each >> method, I have to call both setMethod and setGeneric (or both >> setReplaceMethod and setGeneric). I would like a more compact grammar >> so that I can reduce the key strokes. I'm wondering if there is a >> better way available. >> >> setClass( >> Class='A', >> representation=representation( >> x='numeric' >> ) >> ) >> >> setMethod( >> f='initialize', >> signature='A', >> definition=function(.Object,x){ >> cat("~~~ A: initializator ~~~\n") >> .Object<-callNextMethod(.Object,x=x) >> return(.Object) >> } >> ) >> >> setGeneric('getx', function(object){ >> standardGeneric('getx') >> } >> ) >> >> setMethod('getx', 'A', >> function(object){ >> return(obj...@x) >> } >> ) > > in some sense getx is redundant; x(obj) can only extract a value; more so > with setx(obj) <- value and x(obj) <- value (illustrating partly that 'x' is > a poor name for a slot). > >> >> setGeneric('setx<-', function(.object,value){ >> standardGeneric('setx<-') >> } >> ) >> >> setReplaceMethod(f='setx', signature='A', >> def=function(.object,value){ >> .obj...@x<-value >> return(.object) >> } >> ) > > one can create ad hoc getter / setter writers (e.g., in the Bioconductor > GSEABase package), but in the long run I have found these to require more > thought than the saved keystrokes are worth. You might be more clever / > disciplined than I. It's tempting to write getters / setters as simple > functions (setGeneric / setMethod is required because the defined 'generic' > isn't really that generic, it's just an idiosyncratic accessor) but in the > long run this also doesn't seem to work well.
I just gave some examples on getters and setters. But I didn't only mean getters and setters. Other methods also need the associated two functions (setGeneric and setMethod) for their definition. I'd wish there is a more cleaner way to define a method. One drawback of the current way is the redundancy in the code. For example, 'getx' appears twice (in both setGeneric and setMethod). This redundancy causes a higher maintenance cost than if there were no such redundancy. >> a=new(Class='A',x=10) >> print(getx(a)) >> >> setx(a)<-5 >> print(getx(a)) >> >> ______________________________________________ >> R-help@r-project.org mailing list >> https://stat.ethz.ch/mailman/listinfo/r-help >> PLEASE do read the posting guide >> http://www.R-project.org/posting-guide.html >> and provide commented, minimal, self-contained, reproducible code. >> > > > > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.