Why are protected variables not allowed by default

2019-02-11 10:38发布

问题:

I get a lot of warnings in eclipse like these:

Variable 'myVariable' must be private and have accessor methods.

I think I get them because I didn't set protectedAllowed manually to true in eclipse. But why is it set to false by default? Shouldn't I use protected attributes?

回答1:

Theoretically, protected attributes (variables) are an anti-pattern in object-oriented languages. If only subclasses need to access member attributes of its superclass, define the attributes themselves as private and create protected accessor methods (getter and setter). This approach applies the concept of 'information hiding'. There is an alternative solution: define protected immutable (final) member attributes.

Further readings:

  • Should you ever use protected member variables?
  • http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html


回答2:

I guess, making everything private is an anti-pattern. Often classes are used in a bunch and as a whole represent encapsulated entity placed in separate package. They do not need to hide something from each other, but this rule enforces hiding for no good reason, increasing clutter and effectively making style (as I understand it) worse. Meanwhile, we often see that every class in package is public. I guess this is much worse, but checkstyle doesn't check that.

Encapsulation exists not only on class level, put also on package, system and so on. And I think that these levels are even more important.



回答3:

Allowing package access simplifies programming within a package, and reduces boilerplate code. Often times, access is only needed from within the package. Private access forces you to create a lot of nearly useless accessor methods. This actually has the effect of reducing encapsulation and information hiding because a class has to expose internal data/structure application wide instead of just package wide through public accessor methods. The default package visibility also makes testing easier because test classes live in the same package as well (in test dir/tree).