[Tutor] Design - getFoo and setFoo methods

alan.gauld@bt.com alan.gauld@bt.com
Thu, 16 May 2002 17:41:40 +0100


> When do you use getFoo() and setFoo() methods in your 
> classes? 

There are a few good answers to this and a lot of bad ones!

getXXX/setXXX makes sense if the XXX is a property accessed 
via a common protocol(like in JavaBeans) by a Tool (like a 
GUI builder). 

They also make sense if you put valuidation code in the 
set method to check the values lie within constraints.
Or put security checks to make sure the user has valid 
access rights.

But as a general principle they are a bad idea since they 
basically break the principle of data hiding. You should 
access objects using a behaviourally focussed API and 
the internal function of the methods should determine 
the data held. The data(attributes) should only be there 
to support the methods. Of course the methods may be 
there to expose data but usually this will be ion a lump 
not single attributes(eh a getAddress() method retuirns 
several fields not just one and a getAddressString returns 
the sae info as a single string. How it is stored internally 
is unknown and irrelevant to the class user.

> said they did not usually use them, eg. they access 
> attributes directly.

Thats a common Python idiom but if you are accessing too 
many attributes directly it suggests the class is missing 
some methods. Theres an OOP expression for this called the 
Law of deMeter if you want more research material - try the
Cetus Links page.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld