Class design: accessing "private" members

Steven D. Arnold stevena at neosynapse.net
Fri Jun 30 15:03:55 EDT 2000


At 02:15 PM 6/30/2000 +0200, Jerome Quelin wrote:

>Then, is it better/cleaner to access private members with accessors or not?
>Is it a matter of style? Or are there hidden caveheats using (or not using)
>accessors? It _seems_ cleaner to use accessors, but man, it's quite awkward.

If you always use accessors, then you can store or derive the value in any 
way you wish internally in your class.  You may completely change the way 
the value is obtained, and the class user doesn't need to change anything 
in their code.  This makes upgrading the functionality of your class very 
easy -- for example, you could add alternate methods by which the class can 
obtain values.  Furthermore, if you use accessors you can do a lot of 
tricks that are much more difficult without them, such as logging every 
time a value is set or accessed, or taking multiple actions when a value is 
set.  Even if you don't need to do these things right now, if you don't 
religiously use accessors, sooner or later you will want to do that and it 
will be more difficult to do so when the time comes.  In this sense, it's 
definitely cleaner and more scalable to always use accessors.

Having said all that, I admit a little hypocrisy: in short scripts on rare 
occasions, I do not use accessors.  Sometimes they're more trouble than 
this script is worth.  However, beware of that sort of thinking.  Little 
throwaway scripts very often end up hanging around a long time and it's 
good to craft every line of code carefully with that in mind.


steve


--
Steven D. Arnold           Que quiero sera         stevena at neosynapse.net
"If you have  built castles in the air, your work  need not be lost; that
is where they should be.  Now put the foundations under them!" -- Thoreau





More information about the Python-list mailing list