javacoding-styleclass-visibility

Improvement of package-private classes in Java


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:

Problem with using public instead:

The current workaround:

Questions:

  1. Wouldn't it be useful to come up with a new visibility modifer/alternative?
  2. Is something along these lines already in pipeline?
  3. Are frameworks like Spring/Guice sufficient replacements?

Solution

  • 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

    package company.module.domain
    
    class Example {
      private[module] def moduleMethod = ???
      private[domain] def domainMethod = ???
    }
    

    In this example moduleMethod is available everywhere inside package module and its child packages (like domain). Method domainMethod is visible only in domain 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