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:28

I would use Parameter Annotations, Reflection and a generic validator class to create an app-wide facility. for example, you can code a class method like:

.. myMethod( @notNull String x, @notNullorZero String y){

if (Validator.ifNotContractual(getParamDetails()) {
    raiseException..
    or 
    return ..
}

}

The class methods are "marked up" to annotate their contract requirements. Use reflection to automatically discover the params, their values and annotations. Send it all to a static class to validate and let you know the outcome.

查看更多
男人必须洒脱
3楼-- · 2019-04-09 13:32

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.

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);
}
查看更多
登录 后发表回答