我怎样才能把验证我的方法输入参数的约束?

我怎样才能把验证我的方法输入参数的约束?

问题描述:

下面是实现这一目标的典型方式:

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

我觉得这个解决方案是丑陋的。你的方法迅速填补了样板code检查有效的输入参数的合同,模糊方法的心脏。

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验证规格,那是因为我借了他们。 Unfortunitely他们似乎没有这样的工作方式;它们旨在用于通过校验注释实例变量,然后运行该对象

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设计由-contract框架提供最接近的功能,我的喜欢有的例子?即抛出应该是运行时异常(如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()方法。所以,你可以重写code张贴到:

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);
}