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

前端 未结 1 1331
闹比i
闹比i 2021-01-22 18:55

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

public class Outer {

    private static class Inner { /         


        
相关标签:
1条回答
  • 2021-01-22 19:29

    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.

    0 讨论(0)
提交回复
热议问题