简体   繁体   English

为什么Checkstyle中默认不允许使用受保护的变量?

[英]Why are protected variables not allowed by default in Checkstyle?

I get a lot of warnings in eclipse like these: 我在eclipse中得到了很多警告:

Variable 'myVariable' must be private and have accessor methods. 变量'myVariable'必须是私有的并且具有存取方法。

I think I get them because I didn't set protectedAllowed manually to true in eclipse. 我想我得到它们是因为我没有在eclipse中手动将protectedAllowed设置为true。 But why is it set to false by default? 但是为什么默认设置为false? Shouldn't I use protected attributes? 我不应该使用受保护的属性吗?

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). 如果只有子类需要访问其超类的成员属性,则将属性本身定义为private,并创建受保护的访问器方法(getter和setter)。 This approach applies the concept of 'information hiding'. 这种方法适用于“信息隐藏”的概念。 There is an alternative solution: define protected immutable (final) member attributes. 还有一种替代解决方案:定义受保护的不可变(最终)成员属性。

Further readings: 进一步阅读:

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. 我想这更糟糕,但checkstyle不会检查。

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. 而且我认为这些水平更为重要。

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). 默认的包可见性也使测试更容易,因为测试类也存在于同一个包中(在测试目录/树中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM