In my experience, package-private visibility for classes in Java is turning out to be redundant.
Package-private visibility seems to be based on the premise that a class which is almost-privately used by another class is likely to be kept in the same package. Often this is not the case. Is someone exploring an improved access modifier/alternate mechanism?
Problem with trying to use package-private visibility:
- We are tempted to put functionally unrelated classes in same package to get this benefit
Problem with using public instead:
- APIs get polluted. Once a library Jar is imported, client sees several other public classes that he has no need to be worried about
- From a coding-standards perspective, there is no easy way to ensure that short-circuit calls are not done by developers on time crunches (By short-circuit calls I mean method calls that bypass a layer (like from Servlet direct to DAO bypassing the bean/BO)
The current workaround:
- To dissuade short-circuit calls we usually package different parts of the application into several JARs and ensure only the respective JARs are available in the build environment for each build. (For example server.jar would not be available while compiling swing client classes. Only client classes and common.jar would be available.)
Questions:
- Wouldn't it be useful to come up with a new visibility modifer/alternative?
- Is something along these lines already in pipeline?
- Are frameworks like Spring/Guice sufficient replacements?
Yes, I think it would be useful.
I think what you are looking for is project jigsaw which will eventually make it into Java 9. I am not an expert on this, but you can have a look at the following questions and their answers to get an idea:
I don't have experience with these frameworks.
Looks like a feature from
scala
. There is a scope for access modifiers. I've found this tutorial useful.Method can be private in scope of some package
In this example
moduleMethod
is available everywhere inside packagemodule
and its child packages (likedomain
). MethoddomainMethod
is visible only indomain
package and invisible outside.Unfortunately this functionality is not compatible with
java
and those restriction are compiled to byte code with lost of restrictions i.e. to public