r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
407 stars 56 forks source link

`protected`? #54

Closed robertzk closed 7 years ago

robertzk commented 9 years ago

What do you think of supporting a protected list? These would be methods that can be accessed by other instances of the same R6 class (you can even borrow the friend concept from C++ and specify "friend" classes).

I found I've had to go through hoops to work with private members that have to be modified by other instances of the same class but shouldn't be exposed to the public (e.g., by shuffling around proxy objects).

The most naive implementation is to intercept any calls to protected methods and members and look up the parent.env chain of the calling environment to see if it belongs to the same R6 class, but I can think of more. If you're receptive, I could provide a prototype pull request and sketch it out if the feature seems reasonable and doable.

robertzk commented 9 years ago

Great work on R6, by the way! I was able to drop it in as a replacement to reference classes in a very complicated class with almost no hassle.

wch commented 9 years ago

Hm... sounds like the implementation would be complicated. If you can come up with a relatively simple way to accomplish this, I'd look at it. It doesn't have to even be a full PR right away - just a rough illustration of how it would work.

But bear in mind that one of the design goals of R6 is simplicity. :)

kenahoo commented 9 years ago

"Protected" is probably the wrong name for this if it truly means that the methods/fields are available to other instances of the same class. In Java (the de facto standard for concept naming, at least), this is true even for "private" members/fields. "Protected" in Java means that subclasses (not just the same class) can also access it.

@robertzk If you can find a way to do what you're proposing, I'd argue that it should be folded right into the existing implementation, so that a class's code can always access the methods/fields of another object of its same class, no matter its visibility level. Since right now any such access would be an error, it could be added without breaking anything.

hadley commented 7 years ago

This is out of scope of R6, which is deliberately as minimal as it possible can be (but no more).