微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Preconditions库为notNull检查抛出IllegalArgumentException

你知道 Apache Commons ValidateGuava Preconditions一个不错的替代品,当检查对象是否为空( Spring Assert除外)时会抛出IllegalArgumentException而不是NullPointerException吗?

我知道Javadocs说:

Applications should throw instances of this class [NullPointerException] to indicate other
illegal uses of the null object.

不过,我只是不喜欢它.对我来说,NPE总是意味着我只是忘了在某个地方获得null引用.我的眼睛是如此受过训练,我可以发现它以每秒几页的速度浏览日志,如果我这样做,那么我的头脑中始终会启用bug警报.因此,如果将它抛到我期望IllegalArgumentException的位置,那将是非常令人困惑的.

我有一个豆子:

public class Person {
  private String name;
  private String phone;
  //....
}

和服务方法

public void call(Person person) {
  //assert person.getPhone() != null
  //....
}

在某些情况下,一个人没有电话可能没问题(我的奶奶不拥有任何电话).但是如果你想打电话给这样的人,对我而言,它会调用带有IllegalArgument的调用方法.查看层次结构 – NullPointerException甚至不是IllegalArgumentException的子类.它基本上告诉你 – 再次尝试在null引用上调用getter.

此外,已经有讨论,我完全支持this很好的答案.所以我的问题只是 – 我是否需要像这样做丑陋的事情:

Validate.isTrue(person.getPhone() != null,"Can't call a person that hasn't got a phone");

有我的方式,或者是否有一个库只会抛出IllegalArgumentException进行notNull检查?

解决方法

由于这个问题的主题演变为“正确使用IllegalArgumentException和NullpointerException”,我想指出有效Java项目60(第二版)中的海峡前瞻性答案:

Arguably,all erroneous method invocations boil down to an illegal argument
or illegal state,but other exceptions are standardly used for certain kinds of illegal
arguments and states. If a caller passes null in some parameter for which null values are prohibited,convention dictates that NullPointerException be thrown rather than IllegalArgumentException. Similarly,if a caller passes an out-ofrange value in a parameter representing an index into a sequence,indexoutofboundsexception should be thrown rather than IllegalArgumentException.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐