【问题标题】:Why creating protected properties in beans is counted a bad practice?为什么在 bean 中创建受保护的属性被认为是一种不好的做法?
【发布时间】:2010-02-17 19:22:26
【问题描述】:

我的意思是:

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
   ...
}

第二个例子也是不好的做法吗?

【问题讨论】:

    标签: java oop conventions javabeans


    【解决方案1】:

    一般来说,受保护的变量违反了面向对象的原则。您正在让其他对象直接访问成员变量。通过这样做,您形成了更紧密的耦合,并且使更改变量变得更加困难,因为其他对象直接使用它。这也意味着您无法执行设置时进行验证、围绕 getter/setter 添加日志记录等操作。

    【讨论】:

      【解决方案2】:

      例如,如果您将 PropertyChangeListener 注册到 bean 的属性,则如果子类直接更改受保护的属性,则可能不会通知任何注册的侦听器。

      【讨论】:

        猜你喜欢
        • 2013-09-13
        • 1970-01-01
        • 2010-11-09
        • 2010-10-22
        • 2011-11-20
        • 1970-01-01
        • 2010-10-15
        • 2018-01-25
        相关资源
        最近更新 更多