【发布时间】:2011-03-01 04:17:05
【问题描述】:
如果你有一个类接受一些参数但它们都不允许是null,那么最佳实践是什么?
以下是显而易见的,但例外有点不明确:
public class SomeClass
{
public SomeClass(Object one, Object two)
{
if (one == null || two == null)
{
throw new IllegalArgumentException("Parameters can't be null");
}
//...
}
}
这里的异常让你知道哪个参数是空的,但是构造函数现在很丑:
public class SomeClass
{
public SomeClass(Object one, Object two)
{
if (one == null)
{
throw new IllegalArgumentException("one can't be null");
}
if (two == null)
{
throw new IllegalArgumentException("two can't be null");
}
//...
}
这里的构造函数更简洁了,但是现在构造函数代码实际上不在构造函数中:
public class SomeClass
{
public SomeClass(Object one, Object two)
{
setOne(one);
setTwo(two);
}
public void setOne(Object one)
{
if (one == null)
{
throw new IllegalArgumentException("one can't be null");
}
//...
}
public void setTwo(Object two)
{
if (two == null)
{
throw new IllegalArgumentException("two can't be null");
}
//...
}
}
这些样式中哪种最好?
或者有没有更广泛接受的替代方案?
【问题讨论】:
-
我推荐2号。仅仅因为它看起来很丑并不意味着它不合适。请记住,代码是供人类阅读和理解的,而不是机器。
-
第二种和第三种方法之间的行为差异对于合理回答这个问题非常重要。第二个允许设置者之后将值设置为
null。如果您想要一致的行为,那么您无论如何都应该选择 3,这不再是样式问题。 -
@BalusC 假设 2 和 3 都有二传手。如果 2 没有任何 setter 方法,那么它与 3 基本相同;除非用户可以在创建对象后设置对象。
标签: java constructor null coding-style