As a
Java geek, I am well versed in
its four levels of visibility to class members
(be they fields,
methods,
constructors or
classes).
However, sometimes I find myself wanting
just a little more.
The most restrictive level is
private which hides
visibility to the item from all other classes. Here is
an example of the use of private:
public class Foo
{
private int count;
public int getCount() { return count; }
public void inc() { count++; }
}
So no other class can access
count directly. They
have to do it through
getCount() and
inc()
which limits the possible values of
count (
i.e. it will
only increase) which, of course, is the whole point
of using levels of visibility.
(In this example....
In the general case, I would say the point
of using these visibility modifiers is to
better express the design
of the software in the code.)
So
private is the most
restrictive level you could ever need, right?
Wrong! Consider this example:
public class Link
{
private Link next;
private void setNext(Link n) {
// This is good ... we can set our own next field.
//
next = n;
//
// note: we could have written "this.next = n"
// keep that in mind...
}
private void addBug(Link n) {
// The compiler allows this, but does it make
// any sense? We are changing the next field
// of another object!
//
n.next = null;
}
}
In some cases the
idiom used in
addBug() makes
a lot of sense. But in some cases I have found myself
wanting to disallow it.
Which is why one might want
paranoid.
The idea of
paranoid visibility is that there is
a distinction
between Java's
this (used explicitly or implicitly)
and other objects of the same class. So consider
this
final example:
class Foo
{
paranoid String _name;
public Foo(String name) {
_name = name;
}
public void doStuff(Foo foo) {
// we can change the name of this object
this._name = "whatever";
// compiler error! can't change the name of foo!
foo._name = "dude!";
}
}
So there it is:
public,
protected,
package,
private and
paranoid!
The mystical
fifth level of visiblity in Java.
One could hack up a
compiler to implement this,
if one were so inclined,
but then you would not be
coding
pure Java.
Note to -brazil-: Thank's for reminding
me about private protected! I just did a writeup
there. However I'm pretty
sure that private protected had a different
meaning than the theoretical paranoid
which I am describing here.