How can I place validating constraints on my metho

2019-04-09 12:42发布

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.

Here's what I'd like to have:

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

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.

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.

8条回答
等我变得足够好
2楼-- · 2019-04-09 13:12

Not a fully working solution, but JSR-303 has a proposal for a method-level validation extension. Because it's just an extension proposal just now, implementations of JSR-303 are free to ignore it. Finding an implementation is a little more tricky. I don't think Hibernate Validator supports it yet, but I believe agimatec-validation has experimental support. I've not used either for this purpose so I don't know how well they work. I'd be interested in finding out though, if someone gives it a go.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-09 13:13

There is a small Java Argument Validation package, implemented as Plain Java. It comes with several standard checks / validations. And for those cases where someone need its own more specific validations, it comes with some helper methods. For validations that occur multiple times, just extend the interface ArgumentValidation, with your own And create the implementing class that extends from the class ArgumentValidationImpl.

查看更多
何必那么认真
4楼-- · 2019-04-09 13:15

Jared pointed you to various frameworks that add support for DBC to Java.
What I found to work best is: simply document your contract in the JavaDoc (or whatever Documentationframework you use; Doxygen has support for DBC tags.)
Having your code obfuscated by a lot of throws and checks of your arguments isn't really helpful to your reader. Documentation is.

查看更多
迷人小祖宗
5楼-- · 2019-04-09 13:17

This doesn't directly answer your question, but I think that part of your problem is that you are overdoing the validation. For instance, you could replace the first test with:

if (x.isEmpty()) {
    throw new IllegalArgumentException("x cannot be empty");
}

and rely on Java to throw a NullPointerException if x is null. You just need to alter your "contract" to say that NPE is thrown for certain types of "you called me with illegal parameters" situations.

查看更多
相关推荐>>
6楼-- · 2019-04-09 13:18

If you're using Java 8, lambdas can be used to create a very elegant and readable solution for validation:

public class Assert {

    public interface CheckArgument<O> {
        boolean test(O object);
    }

    public static final <O> O that(O argument, CheckArgument<O> check) {
        if (!check.test(argument))
            throw new IllegalArgumentException("Illegal argument: " + argument);
        return argument;
    }
}

You use it like:

public void setValue(int value) {
    this.value = Assert.that(value, arg -> arg >= 0);
}

The exception will look like:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal argument: -7
    at com.xyz.util.Assert.that(Assert.java:13)
    at com.xyz.Main.main(Main.java:16)

The first nice thing is that the above Assert class is all that's needed really:

public void setValue(String value) {
    this.value = Assert.that(value, arg -> arg != null && !arg.trim().isEmpty());
}

public void setValue(SomeObject value) {
    this.value = Assert.that(value, arg -> arg != null && arg.someTest());
}

Of course that() can be implemented in a number of ways: with a format string and arguments, to throw other kinds of exceptions, etc.

It does not, however, need to be implemented to perform different tests.

Not that you can't pre package tests if you like to:

public static CheckArgument<Object> isNotNull = arg -> arg != null;

Assert.that(x, Assert.isNotNull);

// with a static import:

Assert.that(x, isNotNull);

I have no clue if this is bad for performance or not a good idea for some other reason. (Just started looking at lambdas myself but the code seems to run as it should...) But I like that Assert can be kept short (no need for dependencies that may not be crucial to the project) and that the tests are very visible.

Here's a method for a better error message:

public static final <O> O that(O argument, CheckArgument<O> check,
    String format, Object... objects) 
{
    if (!check.test(argument))
        throw new IllegalArgumentException(
            String.format(format, objects));
    return argument;
}

You call it like:

public void setValue(String value) {
    this.value = Assert.that(value, 
        arg -> arg != null && arg.trim().isEmpty(), 
        "String value is empty or null: %s", value);
}

And out comes:

Exception in thread "main" java.lang.IllegalArgumentException: String value is empty or null: null
    at com.xyz.util.Assert.that(Assert.java:21)
    at com.xyz.Main.main(Main.java:16)

Update: If you want to use the x = Assert... construction with a prepackaged test, the result will be cast to the type used in the prepackaged test. So it must be cast back to the type of the variable... SomeClass x = (SomeClass) Assert.that(x, isNotNull)

查看更多
等我变得足够好
7楼-- · 2019-04-09 13:27

I've seen a technique by Eric Burke that is roughly like the following. It is an elegant use of static imports. The code reads very nicely.

To get the idea, here is the Contract class. It is minimal here, but can be easily filled out as needed.

package net.codetojoy;

public class Contract {
    public static void isNotNull(Object obj) {
        if (obj == null) throw new IllegalArgumentException("illegal null");
    }
    public static void isNotEmpty(String s) {
        if (s.isEmpty()) throw new IllegalArgumentException("illegal empty string");
    }
}

And here is an example usage. The foo() method illustrates the static imports:

package net.codetojoy;

import static net.codetojoy.Contract.*;

public class Example {
    public void foo(String str) {
        isNotNull(str);
        isNotEmpty(str);
        System.out.println("this is the string: " + str);
    }

    public static void main(String[] args) {
        Example ex = new Example();
        ex.foo("");
    }
}

Note: when experimenting, note that there may be a bug around doing this in the default package. I've certainly lost brain cells trying it.

查看更多
登录 后发表回答