Search code examples
javaclasspackagesubclassconventions

Java classes with very limited use, but not limited to one class. External or inner?


Say I have an abstract class AbstractBarrelComponent that extends the Component class. The class uses a class named Barrel for some imaginary purpose.

Where should my Barrel class reside, if the only classes that would/can/should ever use it are the AbstractBarrelComponent and its subclasses?

By "reside" I mean should the class be in its own file, Barrel.java, or should it be a package-protected class in AbstractBarrelComponent.java? Is there a common convention for this kind of situation?


Solution

  • Different programmers and organisations use different standards for this and I don't think there is one right answer. The important thing is to pick a standard and stick to it.

    My personal standard is that inner classes are always private. If a subclass needs access to it then it either should be in a outer protected class or access to its methods should be made available via delegation. The only downside to this is that you end up with more small classes. But, frankly, modern clean coding style relies on good IDEs that make it easy to navigate around your code so the need to group classes for navigation has mostly gone away.

    As an aside, I feel it's unfortunate that the designers of Java did not make a distinction between protected for access by subclasses and protected for access by all classes in the same namespace. These are really quite separate use cases. In your situation there's a tendancy to make it an inner protected classes rather than an outer protected classes to restrict access to subclasses. It would have been better if there was a separate keyword for these two uses.