[Tutor] Private and Public variables
Erik Price
erikprice at mac.com
Wed Oct 8 23:32:16 EDT 2003
On Wednesday, October 8, 2003, at 04:16 PM, Alan Gauld wrote:
> It sounds like you use too many getters and setters period!
> :-)
You're probably right but...
> 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.
I understand this in principle and I agree. However, it seems to me
that in some situations, this creates a tight coupling between the
object that contains the data and the object making use of it. For
instance, say you have a DatabaseRecord object that has been returned
by the database API (and say it is a 3rd party API, and the support
contract is invalidated if you modify the source code). If you need to
get the content of the DatabaseRecord, you probably want to call
getValue or something. This can be used portably in many different
parts of the application, because there might be many aspects of the
application that need a String from the database -- however, if you try
to add a method to DatabaseRecord for every case where you need to do
something with the data, then DatabaseRecord becomes clunky and tightly
coupled to the client code that calls it.
In many cases, I agree -- get the object itself to perform the
appropriate behavior. But there are times when you simply want to get
some element of the data contained by an object.
> 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.
Good observation.
> 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! :-(
A great idea -- I never really thought of this before, btw.
>
>> 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.
Your advice is good, and reminds me of another good book on writing
better code that I am still reading: "Refactoring" by Fowler. I will
have to check out the Pragmatic Programmer sometime, but I am not in a
hurry to learn Ruby (though someday I would like to).
Erik
More information about the Tutor
mailing list