james.shade.org
Notebook

Validating the State of Spring Beans – Take Two

Posted in Java, Programming by James on the December 15th, 2006

Just an update to my previous post on the validation of Spring beans. Err, forget all that.

Spring 2.0 introduces the @Required annotation. You need to enable this in your config file:

<bean class =
“org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor”/>

And then you can annotate each required setter with @Required and Spring will barf on startup if that setter is missing from the Spring config.

It seems the annotation processor needs to be declared in each Spring config (if you have multiple config files, as I do).

I would still advocate writing and explicitly calling further validation code if you class needs it, but this is what you want in 99% of cases.

Comments Off

How Plain Are Your POJOs?

Posted in Java, Programming by James on the December 15th, 2006

Back in the old days, when we wanted to write our model objects to the database, we put a bunch of CRUD methods in the classes to make JDBC calls to do what we wanted. This did its job and was easy, if a bit tedious, to program.

We refactored a bit over the years and got a lot of the CRUD out of model objects, but we still had to implement some interface, or rely on slow reflection code to map things to the database.

Then Hibernate came along and finally our model objects didn’t even need to know there was such a thing as a database. Pure, clean, model objects that had data in when we needed it and from which changed data magically reappeared in the database. Nice. We achieved our goal of having model objects just being model objects, POJOs, and abstracted the database handing away to a place we didn’t even know existed in five years ago.

And then we had Spring. Nice clean classes, dependencies being injected, the whole program elegantly concentrating on business logic instead of being littered with, well, whatever it was we used to have to hold our programs together. Suddenly whole new areas of code could be POJOs as well.

All very nice. But I was uneasy. Certainly my classes looked plain, but actually there was a finely balanced symbiosis between Spring and Hibernate and my objects. Yes they were plain old Java objects, but they had to be a very specific type of “plain”. So not really that plain at all, in fact, I couldn’t help thinking, shouldn’t this level of plainness be enforced by some sort of interface?

Well no. This sort of “specific plainness” couldn’t be enforced by an interface. It was in fact, closer to the duck-typing that the Ruby guys make such a racket about. Hibernate and Spring expected the methods to be there and if they were (and did the right thing), all would work, otherwise it wouldn’t.

And that’s where I expected this post to end when I first thought about writing it a couple of months ago. But recently, there have been some developments…

I’ve started using Hibernate 3.2 and JPA with Annotations. Suddenly my not-so-plain-POJO’s are full of javax.persistence and org.springframework imports, and annotations litter the code. It’s as if I’ve refocused my eyes, and the hidden structure imposed by the magic of Spring and Hibernate has materialised into the code.

So is this a good thing? I can declare my setters as @Required to make sure Spring’s config is doing its job, and the Hibernate config has gone away, it’s all in the annotations. So no need for a careful balance between a config file and the code. The various players are still co-dependent, but it’s now a visible and robust symbiosis which will quickly let you know if something’s been upset.

This new found syntactic crud in my code is a bit untidy, but syntax highlighting can help with that, and while I still miss my POJOs, actually deep-down I know they were never that plain.

There are some contentious issues; I think we need to ensure that the things we annotate in our classes are genuinely meta-data about that class rather than specifics of a particular framework. @Required is a Spring annotation, but if a value is required, it’s required regardless of Spring. The maximum length of a String doesn’t change whether we use JPA or some other persistence mechanism. Which things are conceptually “valid” for annotating may be a bit of an area to think about. For example, I don’t think it’s valid to be annotating the Oracle tablespace in which a particular table lives, or the name of a database constraint – so perhaps it’s not valid to be storing table names and column names in the model objects? I don’t know, perhaps we trade some purity of intent for convenience and clarity?

On the whole, I think the new way of doing things is good, and will reduce maintenance overhead by reducing the chance of errors; and where failures occur things will fail early and tell us why.

Annotations don’t complicate the main Java code, but clearly express the contract between your POJO and the hidden forces which work upon it. The benefit of a compiled, typed language is the amount of validation which can take place at compile time (which otherwise you’d have to build into your unit tests anyway), annotations allow us to take that a bit further.

We’re getting closer to methods being able to declare a complete contract for their usage – which would make debugging and maintenance of code much, much easier.

Comments Off

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.