[Tutor] Private and Public variables

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Oct 8 16:02:34 EDT 2003


> What are your experiences in using protected and private attributes?

In C++ you choose. In Smalltalk all attributes are private.
In early OO LISP and DElphi all attributes were public by default.
In Python all attributes are public by default but tricks exist
to make them private(ish).


In practice I don't find any difference in any of the approaches
because as a matter of good practice I access data via methods.
That is I do not use methods like getXXX very often but manipulate
data via behaviour of the object. In al;most every case where a lot of
getXXX/setXXX methods are being used then the law of demeter is
being broken and the basic OOD should be revisited.

> My experience was mostly in Java where I really was paranoid about
> data hiding. These Java habits were carried along

I'm not sure why Java is so paranoid but it does produice an
extremely verbose style of programming. This is one reason
why Java programmers nearly always wind up writing more code
that C++ programmers for the same project! (IMHO)

> they are still with me. I think one of the reason's why is because I
> tend to favor (following the gang of 4) composition to inheritance.

What does that have to do with data hiding (the correct term
for private data)?

> such, it is very important that my classes have clean and small
> interfaces, leaking as little as possible to the outside world.

Clean an small is a good principle, but has nothing(much) to do with
data hiding. It only becomes significant when you define the interface
as being anything that is technically accessible rather than the
published set of methods. If the class author tells you not to use
methods other that X,Y or Z then those are the inteface, use
anything else and you have broken it. Do you want a police state
or one where you can exercise free concience?

> interfaces should also be "recognizable", e.g. they follow the
> interfaces of the Python objects as much as possible.

Again an excellent design principle.

> So, what do you guys think?

I think your design ideas are correct, the need for data hiding
and the implied distrust of your fellow programmers is perhaps
more questionable.

But if you design classes to expose a behavioural interface
then the ability or lack of to directly access data will not
be of any concern to your users.

For example how often do you even think about accessing the
internal data of a file object? Do you even know what
attributes are there? Do you care?

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




More information about the Tutor mailing list