Contextual Validation: Martin Fowler Retread
Join the DZone community and get the full member experience.Join For Free
in my writing endeavors, i've long intended to write a chunk of material on validation. it's an area that leads to a lot of confusion and it would be good to get some solid description of some of the techniques that work well. however life is full of things to write about, rather more than time allows.
some recent readings made me think about saying a few preliminary things on the topic. one common thing i see people do is to develop validation routines for objects. these routines come in various ways, they may be in the object or external, they may return a boolean or throw an exception to indicate failure. but one thing that i think constantly trips people up is when they think object validity on a context independent way such as an isvalid method implies.
i think it's much more useful to think of validation as something that's bound to a context - typically an action that you want to do. is this order valid to be filled, is this customer valid to check in to the hotel. so rather than have methods like isvalid have methods like isvalidforcheckin.
one of the consequences of this is that saving an object to a database is itself an action. thinking about it that way raises some important questions. often when people talk about a context-free validity, they mean it in terms of saving to a database. but the various validity checks that make this up should be interrogated with the question "should failing this test prevent saving?"
in about face alan cooper advocated that we shouldn't let our ideas of valid states prevent a user from entering (and saving) incomplete information. i was reminded by this a few days ago when reading a draft of a book that jimmy nilsson is working on. he stated a principle that you should always be able to save an object, even if it has errors in it. while i'm not convinced that this should be an absolute rule, i do think people tend to prevent saving more than they ought. thinking about the context for validation may help prevent that.
reposted on 03 nov 2011
Opinions expressed by DZone contributors are their own.