Java构造函数样式(检查参数不为空) [英] Java Constructor Style (Check parameters aren't null)

查看:820
本文介绍了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");
        }
        //...
     }
}

这里的异常让你知道哪个参数为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");
        }
        //...
     }
  }

以下哪种风格最好?

推荐答案

第二个或第三个。

因为它会告诉用户您的API发生了什么问题。

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

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

将检查放在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天全站免登陆