"Private" Member Variables

Alan Gauld alan.gauld at btinternet.com
Sat May 29 07:13:20 EDT 2004


On Fri, 28 May 2004 09:56:43 -0700, "Scott Brady Drummonds"
<scott.b.drummonds.nospam at intel.com> wrote:
> necessary.  Given that the very nature of the language precludes any
> compile-time type dependencies I'm wondering if there is any benefit to
> naming variables with leading underscores and providing accessor functions
> like this:
> class C:
>   ...
>   def value(self):
>     return self.__value
>   ...

There is very rarely any good reason to provide getXXX/setXXX
type accessor functions, even in C++ (JavaBeans are something 
of an exception because tools need them). The whole point of
information *hiding* is that external objects can't access your
internal data, they access behaviours. Exposing your data via
accessor functions is still exposing it (albeit with control over
read/write access). But why does another object need your data?
you own it so you should manage it, if something needs doing you
should do it - via a behaviour. Indeed, there is a school of
thought in OOD that says member data is *only* there to support 
the published behaviour.

Now you may want behaviour that returns a bit of data (like bank
account balance) but even in that case, conceptually the balance
could be a calculated value. But if you really must display your
internal data to the world the best way is as a property IMHO.

> why provide an accessor at all?  Why not just allow direct reading and
> writing of the member variable?  Is there something here I'm missing?

There should be very little need to access the data at all if the
class provides the needed set of ehaviours. If you have an
application where objectts are accessing other objects data then
that's usually a sign that the OO Design is broken somewhere.

> What are your thoughts?  How much privacy should I build into my code?

If there is tight dependency between two values such that if
somebody external changed one (through not appreciating the
interdependency) it would make the other semantically inaccurate
then its a good idea to hide them to protect yourself. But if we
allow a certain amount of trust in our fellow programmers all
other variables can be left exposed and we rely on them to use
the behaviour published via the methods and not to mess with the
innards.

That's my personal approach at least...

OTOH If you are putting your objects out as a library for general
consumption you may take a more conservative view based on the
idea that the less things users can break the less work for you.

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Python-list mailing list