Should I refactor static nested classes in Java into separate classes?
class, java, nested, static
Solution
Jorn statement is correct and it's usually manifests itself as the following rule of thumb:
Nested classes should be made private, Meaning that the hold auxiliary logic for the hosting class and nothing more. If you cant make them private- thet probably should not be nested.
The exception is when you define a nested class to allow easy access to the state of the hosting class, in that case you should consider simply merging both classes to increase cohesion.
Problem
I have inherited code which contains static nested classes as: ``` public class Foo { // Foo fields and functions // ... private static class SGroup { private static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>(); public SGroup(int id, String type) { // ... } } } ``` From reading SO (e.g. Java inner class and static nested class) I believe that this is equivalent to two separate classes in two separate files: ``` public class Foo { // Foo fields and functions // ... } ``` and ``` public class SGroup { static Map<Integer, SGroup> idMap = new HashMap<Integer, SGroup>(); public SGroup(int id, String type) { // ... } } ``` If this is correct is there any advantage to maintaining the static nested class structure or should I refactor?