Class design: accessing "private" members

Martijn Faassen m.faassen at vet.uu.nl
Mon Jul 3 14:18:22 EDT 2000


Jerome Quelin <jerome.quelin at insalien.org> wrote:
> "Alex Martelli" <alex at magenta.com> wrote:
>>These are excellent arguments for always using accessors from OUTSIDE the
>>class.  Jerome, however, was talking about using them from INSIDE the class
>>as well, which is a different issue.
> Sure, I'm always using accessors from outside.
> But from inside the class, I don't know which is the best. I feel like the KISS
> rule should apply, but what do you OO gurus think of it ? How far encapsulation
> should go ?

I don't recall exactly, but the OO literature on this issue referes to the
so-called 'Law of Demeter'. It comes in various weak and strong varieties
which differ on this issue. So you may want to do a web-search on that.

My personal opinion is that in Python you should not use accessors
internally until it turns out to be necessary (which may never be). Python
code is easy enough to change, after all. I don't even mind the occasional
public use of attributes. Helped by unit tests this kind of thing can
be changed to accessors fairly easily if necessary. Or I can of course
go the __getattr__/__setattr__ route.

I think the Pythonic way to think about this goes a bit like this:

  * sure, encapsulation is very important in good designs.

  * but, rapid prototyping is very important in coming up with good
    designs, as rapid prototyping allows you to change designs which
    turned out to be not good enough into better ones pretty easily.

  * good testing is important in any case.

  * if you have good testing and rapid prototyping, it's better to wait
    with various incantations (type checking, public/private, accessors)
    until they appear necessary, instead of doing them up-front and wasting
    time. It'll be likely you're wasting time as your up-front design will
    probably not be optimal yet in any case. Your incantations
    may turn out to be unnecessary in the first place!

In my opinion the best solution to attribute access would be to add 
optional getter/setter methods to Python, much like Delphi's properties,
or the facilities Sather and I hear C# provide.

Such a facility can provide for a very clean path from direct attribute
access to use of getters/setters.

Regards,

Martijn 
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list