Let’s say I have a Java class A, which requires a helper class B. That helper class is only used in A, and has no other purpose. Also, B doesn’t need to use A in any way (don’t call methods or access fields).
So, the question is: where to put B?
There are the following options:
-
Static nested class. In my opinion, it just makes code less clear (much more indentation and such).
public class A { ... private static class B { ... } } -
Non-public class in the same source. I like this option.
public class A { ... } class B { ... } -
Non-public class in the separate source. Looks like this option has a little overhead, though.
// A.java public class A { ... } // B.java class B { ... }
For now, I prefer the 2nd option. What are your thoughts on it? What is the best practice?
Are there any authoritative sources on it?
I strongly vote for option (1). The idea is, that class
Bis only needed by classAand option (1) is the only alternative that clearly expresses that intention: classBis part of classA.