如果您有一个接受某些参数但不允许它们为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");
}
//...
}
}
这些样式中哪一个是最好的?
或者是否有更广泛接受的替代方案?