首页 > 解决方案 > Which SOLID principle is violated in the following code?

问题描述

Which SOLID principle is violated in the following code?

public class A {
  void hello(){
    //some code here
  }
}

public class B extends A {
  int i;
  void hello(){
    i++;
  }
}

I think that LSP (Liskov Substitution Principle) is violated because the subclass B cannot be substituted into a variable of type A. I am really not sure about this, and somehow I think that none of the SOLID principles are violated here.

Another thing I have been thinking about is that i is declared without any access modifier. Should this be a violation? If yes, which violation?

标签: javaoopsolid-principles

解决方案


不声明i私有有什么问题?

来自 Effective Java 第 3 版:

如果一个类可以在其包之外访问,则提供访问器方法以保持更改类的内部表示的灵活性。如果一个公共类公开了它的数据字段,那么改变它的表示的所有希望都将落空,因为客户端代码可以广泛分布。

但是,如果一个类是包私有的或者是私有的嵌套类,那么暴露它的数据字段并没有本质上的错误。

我认为它很清楚什么时候需要曝光i,什么时候不需要。

另一方面,LSP 没有被违反,因为你总是可以写

A a = new B();

通常不适合评估含义不明确的类违反了哪些 SOLID 原则(例如类AB您的情况)

但是,如果您知道每个类的(上下文)含义,那么我们可以发表一些评论。(例如一个Employee is-a Person和一个Student is-a Person- 所以 LSP 应该在这里工作 - 你应该能够将一个Employee对象分配给一个Person引用,并且类似的事情Student也适用于对象)


推荐阅读