Validating state may not the most exciting aspect of software development, but it's important for just about all applications. It's also a challenging area, because validation requirements vary from one application to another. The topic of validation is something I've been thinking about for years now, and in this post I will try to outline some of my thoughts about it.
I'll start with a common validation problem. It's one that occurs in many applications I've worked on. I'll call it the Validation Deadlock Problem. Snazzy, huh? Most application allow users to work with data via separate data entry screens. As an example, the application I am currently working on has data entry screens for 'wells' and for 'batteries'. When you create a well, you have to connect it to a battery. Only certain kinds of wells can be allowed to connect to certain kinds of batteries. Let's say for the sake of simplicity that wells and batteries have to be the same 'color'. The first step is to create a battery. Then you can create a well and hook it up to that battery. Once you've established the connection though, you can go back and change the well or the battery. Generally one wishes to validate all objects in an application before they are actually saved to the database. However, that's not always easy. Let's say you've realized that you set up your well/battery combination incorrectly. You had a 'red' well connected to a 'red' battery, but actually both should be 'blue'.
This presents two problems for validation. The first problem is that when you change the battery, you can't just validate its own state alone. You also have to validate the wells connected to it. There is a perfomance cost to validate all the wells connected to a battery every time you make a change on the battery screen, and it may annoy users that editting a single field is slower than they expect. That's the first problem. The second problem is the dreaded validation deadlock: Assuming you bite the bullet and validate all the wells every time you save a battery, you try to change the battery to blue but you get a validation message saying that you have a red well attached to that battery. The difficulty is that you also can't change the well to blue because it's still connected to a red battery. The particularly annoying aspect of this problem is that in order for the user to be able to change both the battery and well(s) to blue, the well object(s) or the battery object must be allowed to go into an invalid state and saved that way to the database, in other words, across transactional boundaries. Generally the goal is to make sure all objects are always in a consistent state before they are persisted, but here that seems impossible. In my next posting I will explore some solutions to the two problems I've described.