如何在我的方法输入参数上放置验证约束?

Rob*_*ell 5 java validation annotations design-by-contract contract

以下是实现此目标的典型方法:

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
Run Code Online (Sandbox Code Playgroud)

我认为这个解决方案很难看.您的方法很快就会填充样板代码来检查有效的输入参数契约,从而模糊了方法的核心.

这是我想要的:

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
Run Code Online (Sandbox Code Playgroud)

如果那些注释看起来像JSR 303/Bean Validation Spec,那是因为我借用了它们.不幸的是,他们似乎并没有这样做; 它们用于注释实例变量,然后通过验证器运行对象.

许多Java按合同设计框架中的哪一个提供了与"喜欢拥有"示例最接近的功能?抛出的异常应该是运行时异常(如IllegalArgumentExceptions),因此封装不会被破坏.

Jar*_*ell 5

如果您正在寻找一个完全成熟的设计合同机制,我将看一下维基百科页面上列出的一些DBC项目.

如果您正在寻找更简单的东西,您可以从google集合中查看Preconditions类,它提供了checkNotNull()方法.所以你可以重写你发布的代码:

public void myContractualMethod(final String x, final Set<String> y) {
    checkNotNull(x);
    checkArgument(!x.isEmpty());
    checkNotNull(y);
}
Run Code Online (Sandbox Code Playgroud)