What's the use of private?

J

Jeff.M

Unless I'm mistaken, private things are inaccessible to everything
else, even subclasses. And it seems that using private makes it
difficult, if not impossible, to extend the class. Protected, on the
other hand, is just like private except that extending classes can use
protected things.

I can't think of any scenario where private would be a better choice
than protected. So what's the use of private?
 
L

Lew

Jeff.M said:
Unless I'm mistaken, private things are inaccessible to everything
else, even subclasses. And it seems that using private makes it
difficult, if not impossible, to extend the class. Protected, on the
other hand, is just like private except that extending classes can use
protected things.

Extending a class is done for very specific reasons and is not a
"one-size-fits-all" technique. As Joshua Bloch points out in /Effective
Java/, one should prefer composition - including a reference to another class
instance - to inheritance.

Keeping methods and instances private not only does not make extending a class
harder, it makes extending a class easier. There is less to extend, and fewer
unintended consequences.
I can't think of any scenario where private would be a better choice
than protected. So what's the use of private?

Most variables in a class should be restricted to private accessibility. Some
methods may be, if they provide internal services to the class or its instances.

This supports the fundamental object-oriented design and programming principle
of "encapsulation" and "information hiding". The details of how a class
implements behavior should be private whenever possible.

Public and protected variables and methods, and to a lesser extent
package-private accessible elements, become part of the class's outer face,
the contract that it must fulfill forever and in all incarnations. Hidden
elements are easier to maintain because they do not affect the rest of the
world directly. When you open access to an element you commit forever to
having that element available to users of the class.

It is a best practice to program to an interface and implement that interface
with no additional public methods.

Private methods help keep the internal structure of a class maintainable and
easy to understand. Otherwise you end up with tangled mega-methods that try
to do too much in one routine.

Private instance variables can be accessed through accessor methods
("getters") and mutator methods ("setters"). Such methods can enforce program
invariants, control side effects, and perhaps even obviate the need for an
instance variable altogether.

Consider an analogy. When you post a (snail-mail) letter at the post office,
you drop it in a box or hand it to a postal clerk. You don't know or care
whether they use a private method of airplane, truck or pony to get the letter
to its destination. They are free to implement different methods /ad lib./.
The precise delivery mechanism is private; the action to "post( Letter letter
)" is public. If ponies become obsolete in favor of suborbital rockets, all
you experience is better service. The postal system is not obligated to
maintain its postal stables because they never made the pony system public.

Hunt around for tutorials on object-oriented programming practices and you
will find better and more complete explanations.
 
L

Lew

Jeff.M said:
That page doesn't answer my question. But thanks for responding.

Actually, that page explains precisely the reason for private methods and
variables, which is precisely what you asked for.
 
J

Jeff.M

Extending a class is done for very specific reasons and is not a
"one-size-fits-all" technique. As Joshua Bloch points out in /Effective
Java/, one should prefer composition - including a reference to another class
instance - to inheritance.

Keeping methods and instances private not only does not make extending a class
harder, it makes extending a class easier. There is less to extend, and fewer
unintended consequences.


Most variables in a class should be restricted to private accessibility. Some
methods may be, if they provide internal services to the class or its instances.

This supports the fundamental object-oriented design and programming principle
of "encapsulation" and "information hiding". The details of how a class
implements behavior should be private whenever possible.

Public and protected variables and methods, and to a lesser extent
package-private accessible elements, become part of the class's outer face,
the contract that it must fulfill forever and in all incarnations. Hidden
elements are easier to maintain because they do not affect the rest of the
world directly. When you open access to an element you commit forever to
having that element available to users of the class.

It is a best practice to program to an interface and implement that interface
with no additional public methods.

Private methods help keep the internal structure of a class maintainable and
easy to understand. Otherwise you end up with tangled mega-methods that try
to do too much in one routine.

Private instance variables can be accessed through accessor methods
("getters") and mutator methods ("setters"). Such methods can enforce program
invariants, control side effects, and perhaps even obviate the need for an
instance variable altogether.

Consider an analogy. When you post a (snail-mail) letter at the post office,
you drop it in a box or hand it to a postal clerk. You don't know or care
whether they use a private method of airplane, truck or pony to get the letter
to its destination. They are free to implement different methods /ad lib./.
The precise delivery mechanism is private; the action to "post( Letter letter
)" is public. If ponies become obsolete in favor of suborbital rockets, all
you experience is better service. The postal system is not obligated to
maintain its postal stables because they never made the pony system public.

Hunt around for tutorials on object-oriented programming practices and you
will find better and more complete explanations.

Hi Lew,

I understand the composition is preferable to inheritance, but that's
not what I'm asking about.

I'm afraid I don't see how private members makes extending easier.
Let's say you wanted to extend some LinkedList class, or whatever, and
the instance variable for the head node is private. Then you couldn't
do anything with it, and you in all probably would find it impossible
to write the code you need to write.

Protected also supports the principle of encapsulation and information
hiding. Any code that uses a class (rather than extends) will not be
able to access protected members. And so I don't think I'd agree that
protected members are part of a class's outer face.
 
J

Jeff.M

Actually, that page explains precisely the reason for private methods and
variables, which is precisely what you asked for.

That page explains information hiding in general. My question is about
private versus protected. Both already support the principle of
information hiding. The only difference is that protected members are
accessible also to sublcasses (any code that is responsible for the
implementation of the object).
 
L

Lew

Jeff.M said:
That page explains information hiding in general. My question is about
private versus protected. Both already support the principle of
information hiding. The only difference is that protected members are
accessible also to sublcasses (any code that is responsible for the
implementation of the object).

And, as that article mentions, inheritance (i.e., protected access) breaks
encapsulation. The advantage of private accessibility is that they are not
accessible to subclasses.
The authors of Design Patterns discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance (Gang of Four 1995:20). The danger is stated as follows:

"Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)

[edit]

The principles discussed in that article are exactly the answer to your
question. Apply what it says to the notion of private vs. protected (or even
package-private) and you have your answer.
 
L

Lew

Jeff.M said:
I understand the composition is preferable to inheritance, but that's
not what I'm asking about.

I'm afraid I don't see how private members makes extending easier.
Let's say you wanted to extend some LinkedList class, or whatever, and
the instance variable for the head node is private. Then you couldn't
do anything with it, and you in all probably would find it impossible
to write the code you need to write.

Classes have to be designed for inheritance. If the 'head' should be
inherited, then it should be declared private. OTOH, if there are special
checks to be made for 'head', such as making sure that it isn't null at the
wrong time, or that it holds the right pair of pointers, or whaterver, then
making the variable protected risks breaking program invariants. In that case
it is better to expose 'head' as a property (via protected getters and
setters) and keep the variable itself private. Thus subclasses are relieved
of a portion of the implementation, and encapsulation is preserved.
Protected also supports the principle of encapsulation and information
hiding. Any code that uses a class (rather than extends) will not be
able to access protected members. And so I don't think I'd agree that
protected members are part of a class's outer face.

Protected access supports encapsulation less than private. The problem with
protected access is that anyone can create a subclass and futz with the
protected thing. Protected does not support encapsulation - the bad premise
leads to bad conclusions. Protected opens up an element, compared to private
or package-private, *breaking* encapsulation.
 
L

Lew

Lew said:
Classes have to be designed for inheritance. If the 'head' should be
inherited, then it should be declared private.

Oops, I meant should be declared *protected*.
 
W

Wojtek

Jeff.M wrote :
Unless I'm mistaken, private things are inaccessible to everything
else, even subclasses. And it seems that using private makes it
difficult, if not impossible, to extend the class. Protected, on the
other hand, is just like private except that extending classes can use
protected things.

But you can access the super class private variables. Just use the
public accessors (getX, setX). Or maybe protected accessors. At any
rate the variable is private and cannot be accessed directly
(encapsulation).

BTW, most modern compilers will see that if a get/set simply accesses
the private variable with no computation, then it maps it directly, so
there are no performance issues.
 
P

Patricia Shanahan

Wojtek said:
Jeff.M wrote :

But you can access the super class private variables. Just use the
public accessors (getX, setX). Or maybe protected accessors. At any rate
the variable is private and cannot be accessed directly (encapsulation).

BTW, most modern compilers will see that if a get/set simply accesses
the private variable with no computation, then it maps it directly, so
there are no performance issues.

If public or protected get/set methods are provided for fields without
thought, there is no maintainability gain and the fields might as well
have had the access permission of the methods. Using get/set is only an
advantage if they relate to logical attributes that are unlikely to
change even if the superclass implementation changes.

Patricia
 
D

Daniele Futtorovic

On 2008-02-17 16:41 +0100, Lew allegedly wrote:

**** DIScLAIMER *****
Only in the present disclaimer does "you" in this post refer directly
to you, Lew.
*********************
Protected access supports encapsulation less than private. The
problem with protected access is that anyone can create a subclass
and futz with the protected thing.

And this is precisely where I veer off. As far as I see the above is the
only substantial, general argument that can be made in favour of private
versus protected. I find that argument unacceptable and its implications
matter for concern.

I do not advocate making everything protected. I would generally
recommend making all variables private. Some types of fields suffer
protected access rather well: JComponent's EventListenerList comes to
mind. What I'm about is the rule of thumb. IMO the rule of thumb should
be: private for fields, protected for methods. That doesn't mean the end
result will have to look like that; it's a rule of thumb, it means that
every time you deviate from it, you should do so with a reason, good one
or bad one.

What pisses me off with the argument given above is this "ah! if I leave
that open they'll futz with my protected thing" attitude (any Freudians
here?). So fucking what? Look lad: I'm extending your classes, and I
KNOW WHAT I'M DOING. And even if I don't? I've extended classes to do
some funny things their original author surely wouldn't have approved
of. I've seen some parts of my libraries extended, or should I say
distorted, such that a reasonably well-conceived structure was
shattered. So what? How are they supposed to learn otherwise? Sure, once
I wasn't there anymore, it may have in some cases led to the
less-than-agreeable outcome of a library becoming messed up. So what? I
do not live off other people's work so this is quite literally not my
own business.

Am I really the only one who's had to wade through the innards of a
public API (I have Swing in mind), battling to twinkle a slight detail,
inaccessible through public means, of its behaviour by extending classes
and cursing its authors because his attempts were crushed by a single,
private variable which he would have needed to access and which he
/knew/ he could access securely or at least was ready to face whatever
bad consequences may have arisen?

Neither do I think classes should be made final. There is one single
case where final classes and heavy-hiding are not only acceptable but
virtually mandatory, and that's where security issues are at stake. But
in all other cases, at least all that come to my mind, all this locking
up tight is but another recurrence of the hysterical attitude inferred
above.

The usual argument I hear goes approximately like this: "don't make a
class or parts of a class extendible unless they're specifically
tailored to be so".
No. Three times no. (no.)
For classes which are made to be extended, especially abstract classes,
the matter is clear. For classes which are destined _not_ to be
extended, also. Which leaves us with a great majority of classes of
which can't be told that extending them would necessarily be a bad
thing. Note: not "*could*" be a bad thing, "*necessarily would*" be a
bad thing. Why should these be locked up? What's so damn wrong about
letting people decide for themselves, taking responsibility for
themselves? What's so damn wrong with assuming there could be other
people beside oneself who know what they're doing? Do you have such a
poor opinion of your code that you can only assume it'll break if
somebody else touches it?
Furthermore, a solid design for a class already carries with it such
techniques as would be necessary to tailor the class for extension use.
IOW, if you have to make a class specifically to be extendible, then
give it a solid design and you've already dealt with half of the job.
There should not be two spheres of design: one design for the class
hierarchy and one for the classes' internals. There should be but one
sphere with different layers: "macroscopic" layers of lower-level,
higher-level and so forth classes, "microscopic" layers inside the
class, with lower-order and higher-order methods et caetera. The whole
design ought to flow naturally from the highest to the lowest layers --
there shouldn't be any no-trespassing zone in between.
Within a class, you would have a gradient of layers from public use (the
"interface"), via general implementation use, to highly specific
implementation use. A smaller or larger, central part of this gradient
qualifies for protected access -- generally speaking. protected access
does not /break/ encapsulation, it is an /essential part/ of proper,
multi-layered encapsulating design.

Consequently, I do advocate against the idea of locking one's own code
up by default. I have yet to be confronted with an argument which would
call for a reversal of the rule of thumb described earlier, and which
would withstand the test of reason.

DF.
 
J

Joshua Cranmer

Jeff.M said:
Unless I'm mistaken, private things are inaccessible to everything
else, even subclasses. And it seems that using private makes it
difficult, if not impossible, to extend the class. Protected, on the
other hand, is just like private except that extending classes can use
protected things.

I can't think of any scenario where private would be a better choice
than protected. So what's the use of private?

Public, package-protected, and protected methods and variables all make
up part of the API for a class. Once you have made a method or variable
any of these types, it becomes a part that *anyone* could use or modify.
You lose some defensiveness. An example helps here:

Suppose that a class, say Widget, has to perform some hairy magic with a
native object peer. People can extend this Widget class to perform
specific tasks, but they don't need to know how to get from Widget's API
to this peer object. Especially, they shouldn't be touching this peer
object. So Widget makes this object peer private to stop people from
touching it.

In addition, variables should almost always be marked private, since
that allows the class to meter access to them for sanity checks and whatnot.
 
P

Patricia Shanahan

Joshua said:
Public, package-protected, and protected methods and variables all make
up part of the API for a class. Once you have made a method or variable
any of these types, it becomes a part that *anyone* could use or modify.
You lose some defensiveness. An example helps here:

Suppose that a class, say Widget, has to perform some hairy magic with a
native object peer. People can extend this Widget class to perform
specific tasks, but they don't need to know how to get from Widget's API
to this peer object. Especially, they shouldn't be touching this peer
object. So Widget makes this object peer private to stop people from
touching it.

In addition, variables should almost always be marked private, since
that allows the class to meter access to them for sanity checks and
whatnot.

Here's another way of looking at the situation. In practice, a program
goes on changing throughout its useful lifetime. The requirements at end
of life are almost impossible to predict during initial design. A lot of
software engineering is about how to make unanticipated changes as easy
as possible.

There are two ways to be wrong:

1. Make something private that should have been protected.

2. Make something protected that should have been private.

Which is easier to fix?

In case 1, the programmer examines the class and decides the best way to
provide the protected feature, which may be as simple as changing
"private" to "protected" on an existing method. The implementation of
the change is within one class and its unit test.

In case 2, the programmer is trying to make a change to the
implementation of the class that is prevented because of the commitment
implied by making the method protected. Some of the extending classes
may be implemented by different companies, and the programmer does not
necessarily know about them, let alone have the power to cause changes
in them. The programmer has to either make the permission change, and
suffer the wrath of owners of subclasses, or workaround the problem,
possibly making the design of the class messier than would otherwise be
the case.

Patricia
 
D

Daniel Pitts

Daniele said:
What pisses me off with the argument given above is this "ah! if I leave
that open they'll futz with my protected thing" attitude (any Freudians
here?). So fucking what? Look lad: I'm extending your classes, and I
KNOW WHAT I'M DOING. And even if I don't? I've extended classes to do
some funny things their original author surely wouldn't have approved
of. I've seen some parts of my libraries extended, or should I say
distorted, such that a reasonably well-conceived structure was
shattered. So what? How are they supposed to learn otherwise? Sure, once
I wasn't there anymore, it may have in some cases led to the
less-than-agreeable outcome of a library becoming messed up. So what? I
do not live off other people's work so this is quite literally not my
own business.

Here's the breakdown...
Private: Only I know how this variable is used or whether or not it *is*
used, or how it will be used *in the future*.
Protected: I know this method will be useful to derived classes (or its
a method I want derived classes to override), therefor I will set in
stone as part of my interface. I will have to support the use of this
member in future versions.
Public: This member does something useful, and will need to be supported
in future versions of this class.

So, making things protected or that could/should be private does expose
yourself to future "embarrassment". You can completely re-arrange your
private members at any time without worry that it'll affect the contract
of your class. Not so with anything more visible.
 
J

jrobinss

Fun topic (who wants to protect his privates, heh? :) ), so here's my
two cents...

I think as usual in these discussions, each is argumenting from his/
her experience. If you've seen too many public stuff, in Java or other
languages, you'll rant for protection; if you've been bugged by code
limitations, you'll rant for public. I'll add that, just like
everyone, I concur that a perfect design makes these issues very easy
(of course draw() is public and numberOfCalls is private!).

Apart from the obvious, my own experience is in industrial prototypes,
meaning lots of code, written by many different people, and often
hacked out quick and dirty to be maintained for more years than
foreseen. :)

I remember writing part of a framework, thus named because you use a
lot of it by inheritance and dynamic loading. I helped the training
team to set up their scenarios, and we discovered together that most
of what they wanted to do was simply impossible because of private
stuff!

So my intake on this, probably far from the theory, and concerning
methods that are not primarily designed for public access, is:
- if it's understandable and more or less robust, make it protected
- if it's really understandable and even more robust, make it public
- if it's a kind of small procedure that stems from cutting up a large
method into small parts, keep it private.
- if it's really not a sub-procedure but rather a utility method, make
it static public, and perhaps even put it in a class of its own (and
of course name it with great care!)

Note that, while off-topic, the latter stems from my frequent
encounters with copy / pasted code. I prefer a class with a single
static public method taking up a grand total of 4 lines, such as
"searchAndRemoveObjectHashInString(String string, Object object)", to
3 classes using the same operation copy-pasted. And you never know
when you're going to need this short piece of code again.

The key in my opinion is understandability and predictibility (does
this word exist?). If a method is not understandable, even when you
spend hours trying to come up with a suitable name, then it's probably
dedicated to the current implementation; another clue is if its
arguments are numerous and specific, so that the caller can't imagine
why you need them. Make it private, no subclass will know how to use
it anyway.

If you can think up a nice name, and it seems to cover all situtations
(such as "writeSubObjectInDb"), even if it could be private, make it
protected. And you can even stop and wonder whether it wouldn't be
nice to make it public.

To answer many about the theory that you have to *maintain* protected
stuff, I have never come across a deprecated method that I would like
to remove or change, and been bothered that it's protected. Perhaps
it's coincidence. I generally extend systems, packages and classes, I
seldom if ever remove stuff.

However, I have many, many times written a subclass for a class that I
never thought would be extended, and been bothered by all those
privates where protected would make my life easier. That's why I don't
like the idea of a class designed for subclassing, and I agree with
Daniele Futtorovic and others that the whole point of OO is that you
don't yet know if you will need to extend a class. That's also why I
insist so much on clarity of names, documentation and consistency.
When you write a class, you're not writing a sub-procedure for a given
task of yours, you're making your universe richer by one more class,
which may prove to be a useful tool later.

It's as bothering to not be able to extend "private writeInDb" when
this would have been your only change to a class as it is annoying to
extend badly-named and inadequately-publicized "protected writeInDb"
only to discover that in fact the method also updated 30 private
attributes and calls 24 other methods without saying so.

So my point is:
- good naming is the key to good coding, good code should read like
prose (obvious, isn't it?)
- don't make everything private and final, you may regret it later
- don't publicize everything just to avoid the ranting guy on third
floor who wanted to extend your class :)

Have fun
 
J

Jason Cavett

Hi Lew,

I understand the composition is preferable to inheritance, but that's
not what I'm asking about.

I'm afraid I don't see how private members makes extending easier.
Let's say you wanted to extend some LinkedList class, or whatever, and
the instance variable for the head node is private. Then you couldn't
do anything with it, and you in all probably would find it impossible
to write the code you need to write.

Protected also supports the principle of encapsulation and information
hiding. Any code that uses a class (rather than extends) will not be
able to access protected members. And so I don't think I'd agree that
protected members are part of a class's outer face.

Well, to answer your question - keeping variables private, as Lew
said, prevents unintended consequences and also prevents someone from
bypassing sanity checks/error checks/etc.

Taken an ArrayList for example. Let's say the underlying structure is
just your basic array. And say someone made the actual array private
but instead provided a way of adding to the array via a method. This
is *much* better (assuming they did proper error checking) because
someone can extend ArrayList to add additional functionality, but they
won't break the ArrayList by trying to write their own methods for
adding and removing.

It's rare that you want a subclass to get to all of your parts because
there's usually a lot of "stuff" done in the getters and setters that
are required. If you're taking a course right now, or if you are a
beginner programmer, I can see how the argument between private vs.
protected is very easy to make - getters and setters don't do much.
But, as you become more advanced, you should realize that your getters
and setters are doing other things that you don't want someone being
able to break.
 
J

Jason Cavett

So, making things protected or that could/should be private does expose
yourself to future "embarrassment". You can completely re-arrange your
private members at any time without worry that it'll affect the contract
of your class. Not so with anything more visible.

Daniel hit it right on the head. If you're coding a library for a
whole ton of people who will do who-knows-what with it, you cannot
just randomly make changes to your internal workings if they are
relying on that interface. (How much would it suck if you decide to
rename your variables and that affects anybody who is extending your
class?) Instead, by providing access methods (getter/setter), you can
mess around with the inner workings all you want and nobody will know
the difference.
 
D

Daniele Futtorovic

Daniel hit it right on the head. If you're coding a library for a
whole ton of people who will do who-knows-what with it, you cannot
just randomly make changes to your internal workings if they are
relying on that interface. (How much would it suck if you decide to
rename your variables and that affects anybody who is extending your
class?) Instead, by providing access methods (getter/setter), you
can mess around with the inner workings all you want and nobody will
know the difference.

There's no disagreement here: it is my opinion too, and I stated it,
that variables had better, as a rule, be kept private. This means
manipulating the more important of them through getters and
setters, implicitly.
A word, however, on this recurring reference to "rearranging" the
workings of a class. It might be one occasionally has to rearrange
private variables and how they're used. That's a good reason to keep
them private to begin with. But the overall contract of a class is
something that never ought to have to be changed. It may be extended,
but its existing parts should never change. If they have to, then there
was a mistake in the design to begin with, and it should have been given
more thought. There are various techniques for ensuring an existing
class contract will never have to be changed, and they fall into what I
would generally call "good design".

df.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,438
Messages
2,571,699
Members
48,796
Latest member
Greg L.
Top