views:

176

answers:

7

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.

+1  A: 

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);
}
Jared Russell
Preconditions.checkArgument(!x.isEmpty()).
Kevin Bourrillion
Aha, always helpful to have the library creator at hand :)
Jared Russell
A: 

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.

Stephen C
A: 

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.

pmr
The problem is when you ignore, or if you miss, one of the preconditions, then theres no guarantee what behavior your going to get. At best you might get an NPE, at worst you'll end up with some random exception much later on with no idea why it occurred.
Jared Russell
@Jared I agree. But usually there is no better way. Either you bring in an heavy framework and take all the learning and obfuscation overhead or you stick to it. If you really want to use DBC you are best of with a language supporting it natively.
pmr
+1  A: 

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.

Michael Easter
I forgot to mention that there is a subtle advantage to throwing an IllegalArg exception versus a NullPointer. In the case of the former, the API author is clearly telling you something about the contract. (i.e. You are left wondering if you are dealing with a bug.)
Michael Easter
A: 

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.

srini.venigalla
+1  A: 

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.

Verhagen
It comes with a few examples, to get you going.http://java-arg-val.sourceforge.net/usage.html(2 example on this page, and also 3 in the Java Doc (reference to them on top of the given page)
Verhagen
A: 

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.

GaryF