Friday, March 30, 2007

Associating Rules With Object States

If your developing an information management system then its quite likely you'll need to be represent and evaluate large numbers of business rules in your domain model. For example if an Order over £10,000 must be authorized by a Manager then we'll have to represent that somewhere in the domain.

Before looking at how to represent the rules its worth thinking about how you'll evaluate the rules. One option is to have an IsValid property on each domain object that has validation rules, however the question is then "valid for what"?

If we mean persistence then we should rename it as IsValidForPersistence. This might be useful as if an object was valid for its current state (e.g. Active) when it came in from the database then when we save it we will expect it to still be valid for that state.

However although IsValidForPersistence might be useful it doesn't give us all the functionality we'll need because in many cases the validation has to be state based. As an example we don't mind an unauthorized Order over £10,000 sitting in the New state, we only need it to be authorized by a Manager before it moves to the Active state.

We've solved this by using state based rule methods, so you could call order.GetBrokenRulesForTransitionTo(OrderState.Active) and get back a collection of BrokenRule objects with descriptions about the broken rules.

This works very nicely and has allowed our GUI to display a list of reasons that an object can't move to another state whilst at the same time allowing us, in the domain, to ensure that we can avoid state transitions that the object is not yet ready for.

Share This - Digg It Save to Stumble It! Kick It DZone

No comments:

Post a Comment