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

查看:123
本文介绍了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.

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

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

也可以将支票放入二传手,具有相同的详细程度注释。如果您的设置者还具有保持对象一致性的作用,则也可以选择第三个。

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构造函数样式:检查参数不为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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