【发布时间】:2009-03-19 15:18:34
【问题描述】:
有一个Checkstyle 规则DesignForExtension。它说:如果您有一个非抽象、非最终或空的公共/受保护方法,则它不是“为扩展而设计的”。阅读description for this rule on the Checkstyle page 了解基本原理。
想象一下这种情况。我有一个抽象类,它定义了一些字段和这些字段的验证方法:
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();
}
我还有一个 Plant 的子类:
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() 方法不是为扩展而设计的。但是在这种情况下我该如何设计扩展呢?
【问题讨论】:
-
你不应该在不带参数的方法中抛出 IllegalArgumentException...
-
@markt 为了“争论”,我们假设它是 IllegalStateException :)
标签: java inheritance class-design