为什么在 beans 中创建受保护的属性被认为是一种不好的做法?

发布于 2024-08-21 18:07:03 字数 888 浏览 6 评论 0原文

我的意思是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

满栀 2024-08-28 18:07:03

一般来说,受保护的变量违反了面向对象的原则。您允许其他对象直接访问成员变量。通过这样做,您可以形成更紧密的耦合,并且使更改变量变得更加困难,因为其他对象直接使用它。这也意味着您无法执行诸如验证设置时间、在 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.

雨夜星沙 2024-08-28 18:07:03

例如,如果您将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文