Java 构造函数样式:检查参数不为 null
2022-08-31 12:19:31
如果您有一个接受某些参数但都不允许的类,那么最佳实践是什么?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");
}
//...
}
}
这些样式中哪一种最好?
还是有一种更被广泛接受的替代方案?