Edu*_*rch 20 java inheritance class-design
有一个Checkstyle规则DesignForExtension.它说:如果你有一个公共/受保护的方法,它不是抽象的,也不是最终的也不是空的,它不是"为扩展而设计的".请在Checkstyle页面上阅读此规则的说明以获取基本原理.
想象一下这个案子.我有一个抽象类,它定义了一些字段和这些字段的验证方法:
public abstract class Plant {
private String roots;
private String trunk;
// setters go here
protected void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
}
public abstract void grow();
}
Run Code Online (Sandbox Code Playgroud)
我还有一个植物的子类:
public class Tree extends Plant {
private List<String> leaves;
// setters go here
@Overrides
protected void validate() {
super.validate();
if (leaves == null) throw new IllegalArgumentException("No leaves!");
}
public void grow() {
validate();
// grow process
}
}
Run Code Online (Sandbox Code Playgroud)
遵循Checkstyle规则,Plant.validate()方法不是为扩展而设计的.但是在这种情况下我如何设计扩展?
Joe*_*orn 17
该规则正在抱怨,因为派生(扩展)类可以完全替换您提供的功能而无需告诉您.这强烈表明您尚未充分考虑如何扩展类型.你想要你做的是这样的事情:
public abstract class Plant {
private String roots;
private String trunk;
// setters go here
private void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
validateEx();
}
protected void validateEx() { }
public abstract void grow();
}
Run Code Online (Sandbox Code Playgroud)
请注意,现在有人仍然可以提供自己的验证代码,但它们无法替换您预先编写的代码.根据您打算如何使用该validate方法,您也可以将其设为公共最终版.