« iCab 3.0.3 Beta 436 | Main | iCab 3.0.3 Beta 438 - Growl »

Wed, Jan 03, 2007

Explicit Package Visibility?

Happy New Year to all readers of this blog! With 2007 being two and a half days old already, it's about time to express one's wishes for the months to come. So here's my wish for upcoming Java (200)7 beta versions: Add the possibility to explicitely declare package visibiliy. Why?

I'm teaching Java (and related technologies/frameworks) to many different people, beginners as well as Java programmers with years of experience. There's one misunderstanding I encounter regularly: The meaning of the implicit access modifier for default (package) visibility. Consider the following class:

public class Example {
  int value;
  int getValue() { return this.value; }
}

Here, both the variable value and the method getValue() have package visibility since no access modifier is declared explicitely. Currently this is the only way to use the package access level. This often is a problem since many people expect Java to choose the "best" visibility as default, i.e. private for variables. Some even expect methods to be public by default. (You don't think that default public methods are a reasonable assumption? Well, think of interfaces, where all methods are implicitely public and the public access modifier is completely redundant... This absolutely makes sense - but does not make Java easier to use.)

Changing the "default" (implicit) visibility from package to private for variables and from package to public for methods isn't an option since it would break compatibility of existing source code. But there's an elegant solution IMHO that requires only a slight extension of the Java syntax and does not need a new keyword as we can reuse one already existing:

package de.snailshell.wishes;
public class Example {
  private int value;
  package int getValue() { return this.value; }
}

IMHO this source code is easier to understand for beginners and even offers better readability for experienced Java programmers. The access modifier could still be omitted and would still default to package visibility, i.e. source code compatibility remains preserved. Later on, omitting the access modifier could be deprecated for class members (leading to a compiler warning).

Any thoughts on this proposal? Let me know!

[Update] I'm not sure if readability is maintained if the class itself is package visible:

package de.snailshell.wishes;
import ...;
package class Example { ... }

On the other hand, this notation makes it clear that the class is visible in its package only. Because two different lines can start with the same token now, the compiler's parser needs a lookahead of two tokens. I don't know if this would be a problem with the current compiler (maybe it uses a two tokens lookahead already).

Posted by Thomas Much at 12:35
Edited on: Tue, Jan 16, 2007 11:15
Categories: Java