如果您有一个可以接受某些参数但不允许使用任何参数的类,则最佳做法是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");
}
//...
}
}
以下哪种风格最好?
还是有一个更广泛接受的替代方案?