如何在我的方法输入参数上设置验证约束? [英] How can I place validating constraints on my method input parameters?

查看:26
本文介绍了如何在我的方法输入参数上设置验证约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is the typical way of accomplishing this goal:

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

我认为这个解决方案很难看.您的方法很快被样板代码填满,检查有效的输入参数合同,掩盖了方法的核心.

I think this solution is ugly. Your methods quickly fill up with boilerplate code checking the valid input parameters contract, obscuring the heart of the 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,那是因为我借用了它们.不幸的是,他们似乎不是这样工作的.它们用于注释实例变量,然后通过验证器运行对象.

If those annotations look like JSR 303/Bean Validation Spec, it's because I borrowed them. Unfortunitely they don't seem to work this way; they are intended for annotating instance variables, then running the object through a validator.

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

Which of the many Java design-by-contract frameworks provide the closest functionality to my "like to have" example? The exceptions that get thrown should be runtime exceptions (like IllegalArgumentExceptions) so encapsulation isn't broken.

推荐答案

如果您正在寻找成熟的按合同设计机制,我会查看 DBC 的维基百科页面.

If you're looking for a fully fledged design-by-contract mechanism I'd take a look at some of the projects listed on the Wikipedia page for DBC.

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

If your looking for something simpler however, you could look at the Preconditions class from google collections, which provides a checkNotNull() method. So you can rewrite the code you posted to:

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

这篇关于如何在我的方法输入参数上设置验证约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆