java - 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?
解决方案
不声明i
私有有什么问题?
来自 Effective Java 第 3 版:
如果一个类可以在其包之外访问,则提供访问器方法以保持更改类的内部表示的灵活性。如果一个公共类公开了它的数据字段,那么改变它的表示的所有希望都将落空,因为客户端代码可以广泛分布。
但是,如果一个类是包私有的或者是私有的嵌套类,那么暴露它的数据字段并没有本质上的错误。
我认为它很清楚什么时候需要曝光i
,什么时候不需要。
另一方面,LSP 没有被违反,因为你总是可以写
A a = new B();
通常不适合评估含义不明确的类违反了哪些 SOLID 原则(例如类A
和B
您的情况)
但是,如果您知道每个类的(上下文)含义,那么我们可以发表一些评论。(例如一个Employee
is-a
Person
和一个Student
is-a
Person
- 所以 LSP 应该在这里工作 - 你应该能够将一个Employee
对象分配给一个Person
引用,并且类似的事情Student
也适用于对象)
推荐阅读
- mongodb - 为了性能,我应该在 MongoDB 更新命令中具体到什么程度?
- python-3.x - Conda 骨架 pypi:ModuleNotFoundError:没有名为“numpy”的模块
- r - 从 lm 模型对象中提取数据框
- c - 如何使用 GDB 设置具有整数值的双精度变量?
- java - 你如何格式化 GWT Datepicker 月份标签?
- r - R时间序列多线图
- c# - 库中的 ConfigureAwait(true)
- opencv - 您如何将对象检测器应用于给定视频的每一帧?
- python - Python 多处理 - Netmiko
- c++ - 从 GLTF 文件中获取基元总数