Search code examples
javasecurityreflectioncoding-styleencapsulation

Is it needed to declare innards of private nested classes private?


After 1000s of privates in private it occurred to me that it may not be needed

public class Outer {

    private static class Inner { // you may drop static
        private void innerMethod() {}
    }
}

Is there any case that dropping private from innerMethod() would make a difference in encapsulation (or use, by Outer for instance) ? Think also reflection
If not is it recommended to drop it or keep it vis a vis coding style ?

I'd say no and drop but not sure really.

EDIT : just realized that the way I do it is certainly wrong - at least for Inner's fields - declaring those fields private and then using them in the outer class - as this generates ("synthetic") accessors in the bytecode - which is at least bloat. Great - so now I am even more interested to have an account on the security implications of declaring those (Inner's fields, methods used in Outer) package private (or public as @JBNizet says in the comments)


Solution

  • The answer depends on how you currently use inner classes.

    My philosophy for inner classes is to reduce the burden of refactoring. I maintain encapsulation of inner classes: private methods and fields of the inner class are not accessed from the outer class even though they can be. The point of inner classes, then, is to reduce its scope to only the containing class. That way, if later an inner class can be reused elsewhere, it requires almost no work (and a trivial amount of work for non-static inner classes) to move it into its own file.

    Whether or not the above is your style will affect the following reasons for dropping or keeping the private around methods/fields.

    The reasons for dropping private are:

    • The outer class has access to private members and methods of inner classes, meaning such fields/methods aren't really encapsulated
    • Less to type

    The reasons against dropping private are:

    • Making the methods of an inner classes private serves as documentation: the outer class shouldn't use these methods
    • If private is kept, it makes it much easier to promote an inner class to its own file
    • If private is dropped, there are two styles for public inner classes and private inner classes: more for the programmer to think about
    • If private is dropped and the inner class was made public, suddenly everyone who has access to the outer file has access to the inner class's private data

    Given the above style, I think the case against dropping is stronger.