以下是实现此目标的典型方法:
public void myContractualMethod(final String x, final Set<String> y) {
if ((x == null) || (x.isEmpty())) {
throw new IllegalArgumentException("x cannot be null or empty");
}
if (y == null) {
throw new IllegalArgumentException("y cannot be null");
}
// Now I can actually start writing purposeful
// code to accomplish the goal of this method
我认为这个解决方案很丑陋。您的方法很快就会充满检查有效输入参数契约的样板代码,从而模糊了方法的核心。
这就是我想要的:
public void myContractualMethod(@NotNull @NotEmpty final String x, @NotNull final Set<String> y) {
// Now I have a clean method body that isn't obscured by
// contract checking
如果这些注释看起来像 JSR 303/Bean Validation Spec,那是因为我借用了它们。不幸的是,它们似乎并不是这样工作的。它们用于注释实例变量,然后通过验证器运行对象。
哪一个许多 Java 按契约设计框架 http://en.wikipedia.org/wiki/Design_by_contract#Languages%5Fwith%5Fthird-party%5Fsupport提供与我的“喜欢拥有”示例最接近的功能?抛出的异常应该是运行时异常(如 IllegalArgumentExceptions),因此封装不会被破坏。
如果您正在寻找成熟的按合同设计机制,我会看一下 上列出的一些项目DBC 的维基百科页面 http://en.wikipedia.org/wiki/Design_by_contract#Languages_with_third-party_support.
但是,如果您正在寻找更简单的东西,您可以看看前提条件 http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/Preconditions.html来自 google 集合的类,它提供了 checkNotNull() 方法。所以你可以重写你发布的代码:
public void myContractualMethod(final String x, final Set<String> y) {
checkNotNull(x);
checkArgument(!x.isEmpty());
checkNotNull(y);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)