[Rd] Objects in R
Duncan Murdoch
murdoch at stats.uwo.ca
Sun Apr 24 23:15:15 CEST 2005
Seth Falcon wrote:
> Duncan Murdoch <murdoch at stats.uwo.ca> writes:
>
>>What S4 is missing is "encapsulation". Wikipedia's article on
>>object-oriented programming gives a good definition:
>>
>>"Encapsulation - Ensures that users of an object cannot change the
>>internal state of the object in unexpected ways; only the object's own
>>internal methods are allowed to access its state. Each object exposes an
>>interface that specifies how other objects may interact with it."
>>
>>Neither of these properties holds in S4.
>
>
> I don't like the definition of encapsulation in the Wikipedia. If
> nothing else, I think the second part about objects exposing an
> interface specifying how to interact with them should come first ---
> and S4 provides that.
I agree the second part is more important. If you have the second part,
you can handle the first part by convention, e.g. by exposing ways to do
things with the internals through a public interface, and adopting the
convention that you should never go in and meddle directly.
But I don't think S4 does the second part. S4 fixes the representation
of an object, but it doesn't specify how other objects should interact
with it. That's done in other languages through the methods of the
class, but S4 classes don't have any methods, S4 generics have methods.
Generics can be created independently of the class, and the author of
the class will not know to create methods for them.
> In my experience, the ability to create "obvious" interfaces to
> classes is the important part of encapsulation. Python's object
> system, for example, does not (easily) provide protections against
> abuse, but other than some initial misgivings, I've not missed it.
I don't know Python, but a quick look at the reference manual online
makes it look class-oriented like Java rather than generic-oriented like S4.
I think this would be relatively easy to add to R. I'd do it as follows:
Put the class methods in an environment, and put the class slots in a
different one. There would only be one method environment for the
class, but a separate one for each instance. Set the methods
environment to be the parent of each instance's slot environment.
Single inheritance could work by setting the ancestor's method
environment as the parent of the method environment, but it's harder to
handle multiple inheritance. However, since there's only one copy of
the method environment needed, making copies of the methods for each
declared class wouldn't be a big deal.
Duncan Murdoch
More information about the R-devel
mailing list