如果您的类接受某些参数,但这些参数都不允许为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");
}
//...
}
}
这些风格中哪一个是最好的?
或者有没有一种更被广泛接受的选择?
发布于 2010-06-08 21:44:57
第二个或第三个。
因为它会告诉API的用户到底出了什么问题。
要减少冗长,请使用commons-lang中的Validate.notNull(obj, message)
。因此,您的构造函数将如下所示:
public SomeClass(Object one, Object two) {
Validate.notNull(one, "one can't be null");
Validate.notNull(two, "two can't be null");
...
}
将检查放在setter中也是可以接受的,并带有相同的详细注释。如果您的setter还具有保持对象一致性的作用,那么您也可以选择第三种方法。
发布于 2010-06-08 21:50:11
我会有一个实用的方法:
public static <T> T checkNull(String message, T object) {
if(object == null) {
throw new NullPointerException(message);
}
return object;
}
我会让它返回对象,这样你就可以在像这样的赋值中使用它:
public Constructor(Object param) {
this.param = checkNull("Param not allowed to be null", param);
}
编辑:关于使用第三方库的建议,Google的前置条件尤其比我的代码做得更好。然而,如果这是在你的项目中包含这个库的唯一原因,我会犹豫。这个方法太简单了。
发布于 2010-06-09 00:45:27
除了上面给出的答案都是有效和合理的之外,我认为指出检查null可能不是必要的“良好实践”是很好的。(假设除了OP之外的读者可能会认为这个问题很教条)
来自Misko Hevery关于可测试性的博客:To Assert or Not To Assert
https://stackoverflow.com/questions/2997768
复制相似问题