[Tutor] Private and Public variables

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Oct 8 16:16:23 EDT 2003


> definitely use too many getters and setters in Python due to Java
> habits.  And I also tend to use a lot of delegation and composition,
> so I end up masking everything behind an interface.

It sounds like you use too many getters and setters period!
:-)

You should very rarely need to get data from an object.
The object is responsible for managing its own data, if you
are pulling the data out and manipulating it *in any way*
outside of the object then that is bad OOD. Get the object
to do it to itself via a descriptively named method.

If you want the data to feed to another object's method then
again there's something wrong and that methjod probably should
be taking an object as parameter not a primitive value.
Unfortunately this is where languages like Javca/C++ become
unstick because their static type system requires specific
types to be passed so we wind up being forced to extract
more data than should be necessary...

The other broken feature of Java which encourages this
getter/setter business is the fact that Java breans are
defined in terms of a getter/setter inteface to allow
IDEs to build data discovery/introspection mechanisms.

Unfortunately these methods then get mistakenly considered
to be part of the geneal class interface. It might have been
better if Java had used some kind of a IDE keyword to indicate
that these methods should only be used by tool builders! :-(

> learn to relax more when I'm using Python.

That and focussing on defining class behaviours, both in Python
and in Java. Every time you write a metod called getXXX or setXXX
consider why you need it. Could the class itself be doing it
internally via a higher level interface function?

BTW The book "The Pragmatic Programmer" by Hunt and Thomas
covers this topic in more depth. As do many of the writings
of Peter Coad.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list