[Tutor] designing POOP

Alan Gauld alan.gauld at btinternet.com
Mon Feb 11 01:19:51 CET 2008

"Kent Johnson" <kent37 at tds.net> wrote

> Alan doesn't like direct attribute access *or* getters and setters,
> IIUC. He wants all access to the attributes of a class instance to 
> be
> through higher-level methods.

I'd moderate that slightly.
I really, really, don't like getters/setters. So, if you really need 
get at an attribute then use direct access.

However if a real responsibility of the class is to present it's
overall state then I prefer to have a method to do that with state
returned as a whole. For small numbers of attributes that could
be a tuple or for longer sets of data as a dictionary.

Over-use of direct access tends, in my experience, to lead to
the temptation to move code that should be in the class (or a
subclass) into client code. And it is avoidance of that temptation
that is my main reason for providing a values() or state() type
method, rather than using multiple attribute access.

The secondary reason is that a class author should be free
to change the internal data of a class provided he doesn't change
the message interface, but allowing direct access greatly increases
the risk that a change will break some users code. Particularly
if the change involves removing an attribute or converting it to a
derived value.

Of course, as Kent pointed out if you add attributes then
you have the question of whether to modify the state() method
too, which also breaks client code - another reason state()
methods should only return those attributes really needed by
the clients!. They are less likely to change.

> I think it is a good goal and technique to look for higher-level
> methods, and to create classes that are amenable to same, but that 
> on a
> practical level attribute access works and I don't avoid it on 
> principle.

I prefer it to getter/setter but try to avoid it if possible.
Pragmatism means that sometimes its useful or even necessary,
but I always question why I'm doing it and whether I should
instead be adding a method or subclassing.

And to close, the reason I made it an issue in this thread is that
this is about a beginner learning good (P)OOP practice so I
thought it would be good to highlight that direct access
carries risk and is frowned on from a purist OOP perspective

Hopefully this side discussion has done that :-)

Alan Gauld
Author of the Learn to Program web site

> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list