[Tutor] Slightly OT: public/private class members
alan.gauld@bt.com
alan.gauld@bt.com
Fri Feb 14 11:24:06 2003
> My prof says "99% of all data members of a class should
> be private" in a quasi-brainwashed kind of way.
I'd probably argue that it should be more like 75% with the
other 25% as protected...
> when/why would data members/methods need to be private?
Its called information hiding. In good OOP the data is there
to suppoort the methods so you should never need to access
it directly. Making it private enforces that and leads to
greater safety in that only the class owner can manipulate
the data and external classes won't then get broken if the
owner decides to replace anv array with a list say. The
methods using the data stay the same.
> adopted a "we're all consenting adults" point of view
Yes but does allow for private names too using a magic
__xxx naming convention.
> all these "get & set" methods to fetch/set data members from
> an object.
You shouldn't have to write lots of getXXX setXXX methods
only the ones where the data really does need to be exposed
- which should be rare. If you are doing that your design
is almost certainly not object oriented. (I know Java does
this be defaiult but I will restrain myself from saying
any more about Javas design!)
> So, what's the need/use for private members?
To protect the guilty from themselves.
> Sorry if this is OT, but I've not really heard any good arguments that
> support "privatizing" all data members...but then again, I'm
> pretty much a CS rookie.
You're reading the wrong books in that case! Try OOSC by Meyer
or Grady Booch's OOA&D. Both cover the pros/cons of private vv public
members.
[ BTW Its less of an issue in Python since Python data is much more
robust to change than strictly typed languages like Java/C_++
- cf the earlier discussion about typing and static type checking
in Python vv C++ ]
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/