<分区>
我在 Stackoverflow 上多次看到这段代码:
public void doStuff(Object anObject) {
if (anObject == null) {
throw new NullPointerException("anObject can't be null");
}
//rest of the function
}
这是一个针对 null
参数的保护子句,因为将 null
传递给要求参数为非 null 的函数将导致 NullPointerException
.
我了解保护条件对于在其他情况下验证参数的重要性(即检查日期范围、负货币值、无效字符串大小等)。
但是,在 null
的情况下,特别是 抛出 NullPointerException
不是多余的吗?这与稍后让运行时自己抛出 NullPointerException
有何不同?
注意:我以一种语言不可知的方式提问,因为模式本身可以应用于 Java 和 C#。