Sunday, September 17, 2006

Validation II

This is a continuation of my previous posting about validation. When validating attributes on an object, the setting method on the attribute would seem to be the most obvious place for validation logic. However, this presents problems when the object must be validated externally. The first example I described in my earlier post concerned the need to validate all the wells associated with a battery when saving the battery - because changing an attribute on a battery could be invalid given the state of wells already attached to that battery. Since the wells themselves already exist, one wouldn't be calling any of the setting methods! A solution I generally adopt to this kind of problem is to write a 'valid' or 'isValid' method for each domain object - in fact I think it's a good idea (in languages like Java and C#) to define an interface (Validatable?) with this method and to implement it for all domain objects. That way, the valid method can be called after all attributes on an object have been set. This method can then also be called by the battery for each well. In my next posting I will discuss the validation deadlock problem.


Jamie McIlroy said...

I like your interface idea.

What are your thoughts regarding validation through an MVC framework like JSF? Would the validation phase of the JSF lifecycle just call your 'isValid' method on the object in question?

Vladimir Levin said...

I am not familiar with JSF, so I don't know what the validation phase of its lifecycle is about. Nevertheless, I guess I can tentatively answer 'yes'. However, keep in mind that I am talking about domain-level validation. There is also form-level validation, where you might for example make sure that a phone number has the right number of digits. I generally prefer masking to validation in this kind of situation though. In other words, don't let the user enter in a date - have him orher pick a date from a calendar. Don't let users enter in phone numbers completely freeform, have then choose a mask (or if you don't want that hassle, don't validation phone numbers at all).
Hence I think that form-level validation can be completely eliminated in a well-made application.

Jamie McIlroy said...


I'm torn on whether to leverage a framework's validation for Forms (JSF's is...ummm....alright...a bit extraneous when it comes to multi field (can't pick Calgary, British Columbia or can't set an end data before a start date) validation but still does the job.

The purist in me feels a UI is nothing more than an interface, don't validate out on the screen at all, just use the screen to inform the user when something went wrong (as detected by the domain). The practical side says, "dust it...these frameworks are doing a pretty nice job of validating the non-persistent Domain level stuff, use them"

So yeah, torn.