如果您的类接受某些参数,但这些参数都不允许为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");
}
//...
}
}
这些风格中哪一个是最好的?
或者有没有一种更被广泛接受的选择?
https://stackoverflow.com/questions/2997768
复制相似问题