views:

32

answers:

2

I often see people validating domain objects by creating rule objects which take in a delegate to perform the validation. Such as this example": http://www.codeproject.com/KB/cs/DelegateBusinessObjects.aspx

What I don't understand is how is this advantageous to say just making a method?

For example, in that particular article there is a method which creates delegates to check if the string is empty.

But is that not the same as simply having something like:

Bool validate()
{
    Result = string.IsNullOrEmpty(name);
}

Why go through the trouble of making an object to hold the rule and defining the rule in a delegate when these rules are context sensitive and will likely not be shared. the exact same can be achieved with methods.

+1  A: 

There are several reasons:

SRP - Single Responsibility Principle. An object should not be responsible for its own validation, it has its own responsibility and reasons to exist.

Additionally, when it comes to complex business rules, having them explicitly stated makes validation code easier to write and understand.

Business rules also tend to change quite a lot, more so than other domain objects, so separating them out helps with isolating the changes.

The example you have posted is too simple to benefit from a fully fledged validation object, but it is very handy one systems get large and validation rules become complex.

Oded
A: 

The obvious example here is a webapp: You fill in a form and click "submit". Some of your data is wrong. What happens?

  • Something throws an exception. Something (probably higher up) catches the exception and prints it (maybe you only catch UserInputInvalidExceptions, on the assumption that other exceptions should just be logged). You see the first thing that was wrong.
  • You write a validate() function. It says "no". What do you display to the user?
  • You write a validate() function which returns (or throws an exception with, or appends to) a list of messages. You display the messages... but wouldn't it be nice to group by field? Or to display it beside the field that was wrong? Do you use a list of tuple or a tuple of lists? How many lines do you want a rule to take up?

Encapsulating rules into an object lets you easily iterate over the rules and return the rules that were broken. You don't have to write boilerplate append-message-to-list code for every rule. You can stick broken rules next to the field that broke them.

tc.