为什么在 beans 中创建受保护的属性被认为是一种不好的做法?
我的意思是:
public class SomeBackingBean {
protected String someString;
public void setSomeString (String str) {
this.someString = str;
}
public String getSomeString {
return someString;
}
}
这只是一般答案的一般情况。
现在是第二个例子:
public abstract class AbstractBean<T extends EntityInterface> {
protected T entity;
public void setEntity (T t) {
this.entity = t;
}
public void getEntity () {
return entity;
}
protected ReturnType calculateSomethingCommon () {
//use entity (knowing that it implements EntityInterface)
//to implement some common for all subclasses logic
}
}
public class ConcreteBean extends AbstractBean<ConcreteEntity> {
...
//and here we can write only specific for this bean methods
...
}
第二个例子也是不好的做法吗?
What I mean is:
public class SomeBackingBean {
protected String someString;
public void setSomeString (String str) {
this.someString = str;
}
public String getSomeString {
return someString;
}
}
It was just a general case for a general answer.
Now second example:
public abstract class AbstractBean<T extends EntityInterface> {
protected T entity;
public void setEntity (T t) {
this.entity = t;
}
public void getEntity () {
return entity;
}
protected ReturnType calculateSomethingCommon () {
//use entity (knowing that it implements EntityInterface)
//to implement some common for all subclasses logic
}
}
public class ConcreteBean extends AbstractBean<ConcreteEntity> {
...
//and here we can write only specific for this bean methods
...
}
Is second example an example of bad practice too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,受保护的变量违反了面向对象的原则。您允许其他对象直接访问成员变量。通过这样做,您可以形成更紧密的耦合,并且使更改变量变得更加困难,因为其他对象直接使用它。这也意味着您无法执行诸如验证设置时间、在 getter/setter 周围添加日志记录等操作。
In general, protected variables violate object oriented principles. You're giving other objects direct access to member variables. By doing so, you form tighter coupling and it makes it harder to change the variable, since other objects are directly using it. It also means you can't do things like validate when it's set, add logging around getters/setters, etc.
例如,如果您将 PropertyChangeListener 注册到 bean 的属性,则当子类直接更改受保护的属性时,可能不会通知任何已注册的侦听器。
If, for example, you have a PropertyChangeListener registered to properties for a bean, any registered listeners might not be notified if a protected property is changed directly by a sub-class.