[Tutor] Design - getFoo and setFoo methods

Stuart Smith stuart@sharedreality.org
Sun, 19 May 2002 22:37:07 +0100


My understanding of an object is that it represents some entity and 
encapsulates the data and code for manipulating that data.  For example, 
considering a car, the class may define a number of different attributes of 
a car - engine size, fuel efficiency, etc.  A method defined in that class 
could be to return amount of fuel consumed, given an average speed and 
distance.  So basically, if you have something which has attributes and has 
some sort of processing involved, it's a good candidate for making an object.

Deciding what should and shouldn't be an object is sometimes a matter of 
personal style - it all depends on how abstracted you want your code to 
be.  Some things are pretty obvious that they should be objects, some 
aren't.  If you're unsure, have a think about whether the advantages you'd 
gain from making something an object, are worth the extra complexity in the 
code.

get and set methods I have learnt to be useful to make code more 
modular.  By using get and set methods for data in objects, you can change 
how the object represents the data internally without affecting the rest of 
your application.  If you have objects representing people, you might 
decide one attribute should be the person's age.  For this explanation, 
I'll assume other parts of the program need to read the age - not set 
it.  If you later decide that it would be better to store date of birth 
rather than age, you have to change any code that reads that value.  If, on 
the other hand, you use a get method, all you need to do is change the get 
method to work out the age from the date of birth.

Many projects change the data structures they use to represent things and 
if it's a large piece of software it can be awkward having to find every 
occurrence of a directly accessed variable to change the code.  If the 
class that's changed is re-used by several projects (which is one of the 
goals of OO programming), then it becomes even worse.

My two cents.

--
Stuart Smith