java 构造器 null_Java构造函数样式:检查参数不为null

如果您有一个可以接受某些参数但不允许使用任何参数的类,则最佳做法是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");

}

//...

}

}

以下哪种风格最好?

还是有一个更广泛接受的替代方案?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值