james.shade.org
Notebook

Validating the State of Spring Beans

Posted in Java, Programming by James on the September 10th, 2006

I’ve recently started using Spring; and have a couple of projects on the go. One thing which has concerned me is the validation of bean state.

I’m a bit of a stickler for validating the inputs to all my methods, throwing runtime exceptions if invalid data is passed to public or protected methods, and using asserts in private methods.

The rationale for this is fairly obvious – the earlier you spot bad data passing through your application, the quicker you can identify and fix the problem. Bad data propagating through several layers of code can cause problems which are incredibly hard to trace. It’s worth the overhead of the validation on each method (which is tiny, unless you do something stupid), and generally I’d leave assertions enabled on the production environment – they can be invaluable in tracing intermittent problems.

A good explanation of this is in Item 23 of the excellent Effective Java Programming Guide by Joshua Bloch.

Spring (or any other Inversion of Control/Dependency Injection framework) supplies you with complete, ready to use objects. You no longer construct very much at all with code (well, I’m currently experimenting with just how much I get Spring to do, and how my I do with old-fashioned Java). And that’s what’s concerned me – I can’t just trust Spring to give me nice, valid objects.

It’s not a Spring thing, but who’s to say that the person writing the Spring config file will set all of the various attributes of the object appropriately.

Initially I decided that it would be best to instantiate beans via their constructors. This is an option in Spring, and I know this is the favoured means of initialising beans in other frameworks. This is good, as your bean gets properly constructed and you can validate the inputs. However, in the configs you have to specify the arguments to the constructor in the right order (rather than referring to parameters by name), plus you can end up with huge cumbersome constructors on your beans. Gets even more complicated if some parameters are optional. All this makes for unreadable config files and ugly code – which makes for poor maintainability.

Spring handles setter calls much more neatly than constructor calls. So this was the way to go. But when I come to use my bean, how do I know Spring has set all the right setters?

My initial response was to validate the various parameters in my public methods. Generally, using Spring MVC there is only one public method per class and this was the case with most of my classes. I tested the existence of the bean attributes I wanted Spring to set, and threw IllegalStateExceptions if anything was missing. I couldn’t use asserts, because received wisdom is that it’s “bad practice” to use asserts in public methods – because they can be switched off, and you don’t want your public methods unprotected (see above).

As the number of these checks increased, the volume of…

if(someAttribute == null)
{
throw new IllegalStateException(“’someAttribute’ is not set”);
}

…checks began make the code look untidy. And this had to be repeated in every public method of the class.

So I cheated and started using asserts. Now, each public method has a line:

assert assertBeanState();

And each class has a method:

protected boolean assertBeanState()
{
assert someAttribute != null : “’someAttribute’ is not set”;
assert someOtherAttribute != null : “’someOtherAttribute’ is not set”;
…
return true;
}

This has the benefit of each public method only needing a single line, and it can all be switched off in production, if you’re so inclined, because they are real asserts.

All works nicely, is clean and readable code, and makes sense to me.

And, it turns out that my blind belief in “no asserts on public methods” was wrong. As is clearly stated in the Java Language Guide, “Do not use assertions for argument checking in public methods”. Argument checking. I’m not checking arguments to the method, I’m checking bean initialisation state – which is (perhaps) fine to do in an assert.

Of course, asserts being okay in public methods to check bean state is only really valid because I’m using Spring and making some assumptions about how my bean will be used, and only expecting my asserts to check the initial state of the bean as created by Spring. Some rogue programmer could make use of the public setters that Spring requires to break the bean – which wouldn’t be caught if the assertions were off. So perhaps they should be concrete checks rather than wishy-washy assertions?

I’ll stick with assertions for now – while I believe in much validation, it’s perhaps overkill to expect every public method call to check every aspect of the object state (and let’s be fair, why should it stop at the boundary of the object, what about contained objects?). There have to be limits, and common sense should dictate where that limit is.

One Response to 'Validating the State of Spring Beans'

Subscribe to comments with RSS

  1. Darren said, on September 10th, 2006 at 13:08

    I was going to pick you up on the “no asserts in public methods” thing until I read your whole entry. :-)

    I wonder if it would be possible to have some sort of external validation tool that took your spring configs and your source code, and told you if all required setters were being set.
    The annotations stuff in Java 1.5 seems to be tailor-made for this.
    You could even (in theory) make this validation step part of your Servlet startup – a one off check that all is valid and you’re away.