为什么Checkstyle中默认不允许使用受保护的变量? [英] Why are protected variables not allowed by default in Checkstyle?

查看:312
本文介绍了为什么Checkstyle中默认不允许使用受保护的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在eclipse中收到很多警告:

I get a lot of warnings in eclipse like these:


变量'myVariable'必须是私有的并且有访问方法。

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

我想我得到它们因为我没有设置 protectedAllowed 设为true。但是为什么默认设置为false?我不应该使用受保护的属性吗?

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?

推荐答案

从理论上讲,受保护的属性(变量)是面向对象语言中的反模式。如果只有子类需要访问其超类的成员属性,则将属性本身定义为private,并创建受保护的访问器方法(getter和setter)。这种方法适用于信息隐藏的概念。还有另一种解决方案:定义受保护的不可变(最终)成员属性。

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.

进一步的读数:

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

这篇关于为什么Checkstyle中默认不允许使用受保护的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆