No Illegal State Objects

[Actually, I'm not sure that this idea is not somewhere else on the wiki, nor am I sure that this is the best name for this page. So refactor away! Just make sure you change the references to this page, as well.]

I'm a big fan of objects that cannot be in an "illegal" or inconsistent state. This sort of object doesn't need to be checked by its users. Such objects are easy enough to create if you put all of the information the object needs in the constructor, but for objects with dozens of pieces of information, this gets awkward really quickly. On the other hand, having individual setters and getters for each piece of information is easier to code, clearer to read, and easier to use, but opens the possibility of having intermediate states, during all the setting and getting, that should not be allowed for the final state of the object. For example, a postal code and country are required, but the postal code must be valid for the given country. If you can't have a state where a postal code and country are inconsistent, or one or the other doesn't exist, you cannot do anything but set them both in a single method invocation.

My solution? I create a separate object with all of the getters, setters and error checking code that can be in an illegal state, and add an isValid() method to it. Then I can use all of the individual setters and getters, and each can do error checking appropriate to the individal item (e.g., postal code cannot be empty). At the end I invoke isValid() which does the consistency checks between the various fields, and sets appropriate error flags which can be queried. I then pass this SetupObject? to a factory method for the real data object. This factory method checks isValid(), and refuses to create a real object unless the setup object is valid. Now I guarantee that anbody getting the real object is always getting a valid, consistent object, while still having the ability to have inconsistent states while I'm setting up the object.

Updates are done similarly; I ask the data object for a SetupObject?, modify the SetupObject?, and then ask the data object to update itself from the SetupObject? once the SetupObject? is back in a consistent state again.

Is this a pattern? Well, certainly. And surely someone's discovered it before. Is there a name for it? Where is it documented?

CurtSampson


Is this kind of like a BuilderPattern? 'It could be'.


I have this, though I haven't put the checks in the parameter object itself, before. Otherwise its a StateObject which is often used as a transactional argument to an object factory.


EditText of this page (last edited January 31, 2003) or FindPage with title or text search