[Tutor] Accessing class attributes: use methods only?
alan.gauld at btinternet.com
Tue Feb 13 22:41:40 CET 2007
"Chris Lasher" <chris.lasher at gmail.com> wrote
> Is it general good practice to access and set class attributes via
> methods only, or is it okay practice to directly interact with class
Its generally good OOP practice to interact with object via messages.
Its also good practice NOT to access an objects attributes directly
(and that includes via get/set methods) A class should publish a
set of operations. The attributes should be there to support
If you extract a value from a class, mess with it and write it back
again thats *very bad* OO programming, don't do it. Its so important
it even has a law named after it - the Law of Demeter...
That having been said, some objects responsibilities include
exposing some data, but usually in those cases you want a set
of data and it can be returned in a single method via a tuple.
Similarly you can modify the data via a single call.
An example might be a Location class where rather than
having access to each field of the address you simply create
an address by passing a tuple of values, read an address
by retrieving a tuple and modify an address by using the
full tuple. (This also ensures that validation of fields - like
checking the post code still matches - can be done) But
you might also have other operations such as formatting
addresses. caculating distances between addressed (cue
the recent geo thread!) etc.
If you really must expose an attribute you should ideally
make it a property rather than a normal attribute.
> The professor in a class on Perl that I'm taking suggested
> that directly accessing and setting class attributes was a bad idea.
This is true in any OOP environment and the principles of
information hiding apply to classses as much as to modules.
But the really important issue is that classes should express
an operationally focused interface not a data focusssed one.
Most of the time you shouldn't know, nor care, what the dfata
attributes of a class are. You send messages to get things
done, not to extract/insert data.
Polymorphism only works on methods, not data access.
However, one of Pythons core principles is it doesn't get in your way.
If you really must access a bit of object state directly Python lets
you and its not any more wrong than doing it by calling a
getX/setX method. get/set abuses information hiding almost as
much as direct access.
PS. If you really want to find out why access to data is bad
read Parnas' original paper on Information Hiding
(On the Criteria to Be Used in Decomposing Systems Into
Modules). Its probably on the web somewhere I'm sure.
Its from 1972, this isn't anything new... Wikipedia is also
a good source.
Author of the Learn to Program web site
More information about the Tutor