Java构造函数样式:检查参数不为空 [英] Java constructor style: check parameters aren't null

查看:95
本文介绍了Java构造函数样式:检查参数不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个类接受一些参数但不允许它们为 null,那么最佳实践是什么?

What are the best practices if you have a class which accepts some parameters but none of them are allowed to be null?

以下是显而易见的,但例外有点不具体:

The following is obvious but the exception is a little unspecific:

public class SomeClass
{
     public SomeClass(Object one, Object two)
     {
        if (one == null || two == null)
        {
            throw new IllegalArgumentException("Parameters can't be null");
        }
        //...
     }
}

这里的异常让你知道哪个参数是空的,但构造函数现在非常丑陋:

Here the exceptions let you know which parameter is null, but the constructor is now pretty ugly:

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");
        }
        //...
  }

这里的构造函数更简洁,但现在构造函数代码并不真正在构造函数中:

Here the constructor is neater, but now the constructor code isn't really in the constructor:

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");
        }
        //...
     }
  }

以下哪种风格最好?

或者有更广泛接受的替代方案吗?

Or is there an alternative which is more widely accepted?

推荐答案

第二个或第三个.

因为它会告诉您 API 的用户到底出了什么问题.

Because it tells the user of your API what exactly went wrong.

为了减少冗长,使用来自 commons-lang 的 Validate.notNull(obj, message).因此,您的构造函数将如下所示:

For less verbosity use Validate.notNull(obj, message) from commons-lang. Thus your constructor will look like:

public SomeClass(Object one, Object two) {
    Validate.notNull(one, "one can't be null");
    Validate.notNull(two, "two can't be null");
    ...
}

将检查放在 setter 中也是可以接受的,具有相同的冗长注释.如果你的 setter 也有保持对象一致性的作用,你也可以选择第三个.

Placing the check in the setter is also acceptable, with the same verbosity comment. If your setters also have the role of preserving object consistency, you can choose the third as well.

这篇关于Java构造函数样式:检查参数不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆