有一个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();
}
我还有一个植物的子类:
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
}
}
按照 Checkstyle 规则,Plant.validate() 方法不是为扩展而设计的。但是在这种情况下我该如何设计扩展呢?