[Tutor] domain logic and avoiding setters and setters.
alan.gauld at freenet.co.uk
Tue Jul 12 09:11:55 CEST 2005
> So I have been trying to figure out how to get around doing getters
> and setters and still have an oo way to inherit and apply business
I think you are missing the point a wee bit.
The object should not allow you to access its internal data.
You should not *need* to access its internal data.
The object has responsibilities in the form of behaviours.
The internal data is only there to support those behaviours,
it should be of no interest to external objects, therefore
you do not need setters and getters. Its not the setXXX getXXX
thing thats wromg its the very idea that users of the object
would want to access the internal data that is wrong.
In the words of Peter Coad, "Objects do it to themselves"
Now in some applications you do need the internal values,
but usually its as a group. For example an Address class
might have a method to return the full address content,
but rather than provide individuual set/get methods per
field it would return the whole address as a string or
a tuple.(Note that both of these are immutable types!)
In some cases you may actually choose to expose one
particular attribute, in which case a get/set pair for that
one attribute is OK - they represent a genuine responsibility
of the class. (Making it a property might be better still...)
Its providing get/set pairs for *every attribute* that breaks
good OOP practice.
PS. For a more formal description of the above principle
look up "The Law of Demeter" on Google.
Author of the Learn to Program web tutor
More information about the Tutor