views:

32

answers:

1

I am validating constructor and method arguments, as I want to the software, especially the model part of it, to fail fast.

As a result, constructor code often looks like this

public MyModelClass(String arg1, String arg2, OtherModelClass otherModelInstance) {
    if(arg1 == null) {
        throw new IllegalArgumentsException("arg1 must not be null");
    }
    // further validation of constraints...
    // actual constructor code...
}

Is there a way to do that with an annotation driven approach? Something like:

public MyModelClass(@NotNull(raise=IllegalArgumentException.class, message="arg1 must not be null") String arg1, @NotNull(raise=IllegalArgumentException.class) String arg2, OtherModelClass otherModelInstance) {

    // actual constructor code...
}

In my eyes this would make the actual code a lot more readable.

In understand that there are annotations in order to support IDE validation (like the existing @NotNull annotation).

Thank you very much for your help.

A: 

Such frameworks do exist (JSR-330), but firstly, I would debate that the annotation approach is more readable. Something like this would seem better to me:

public MyModelClass(String arg1, String arg2, OtherModelClass otherModelInstance) {
    Assert.notNull(arg1, "arg1 must not be null");
    // further validation of constraints...
    // actual constructor code...
}

where Assert.notNull is a static method somewhere (and as provided in the likes of Spring or Commons Lang).

But assuming you're convinced with using annotations, have a look at Hibernate Validator, which is the reference implementation of the JSR-330 API. This has annotations like the ones you describe.

The problem here is that you need the framework to interpret those annotations. Just calling new MyModelClass() isn't going to do that without some classloading magic under the covers.

The likes of Spring can use JSR-330 annotations to validate the data in models, so you could have a look at that, but that may not be suitable for your situation. Something similar is going to be necessary, though, else the annotations are nothing more than decoration.

skaffman
In fact I'm using spring a lot. Thank you for your help.Maybe you're right and the static "Assert.notNull" approach is the more readable one.
marius