java 函数参数为空,Java构造函数样式(检查参数不为空)

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

}

//...

}

}

Which of these styles is best? Or is there an alternative which is more widely accepted?

解决方案

The second or the third.

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值