Extract Validation rules out from CSLA BO

The first priciple of SOLID rules is SRP, it would be nice if we can extract validataion rules out from BO. And I couldn’t belive it was so easy to do implement.

The classic way:

private void AddCustomRules()
        {
            // Custom validation
            ValidationRules.AddRule<EmailBO>(EmailRoleValidValues<EmailBO>, EmailRoleProperty, 1);

        }

The revised version:

// EmailBO
   protected override void AddBusinessRules()
   {
      EmailRuleFactory.CreateOn(ValidationRules);
   }

public class EmailRuleFactory
{
   public static void CreateOn(ValidationRules rules)
   {
      rules.AddRule<EmailBO>(EmailRoleValidValues<EmailBO>, "EmailRole", 1);
   }

   private static bool EmailRoleValidValues<T>(T target, Csla.Validation.RuleArgs e) where T : EmailBO
   {...}
 

All the validation tests still passed!

Note: I had to expose protect Parent field from BusinessBase. And PropertyInfo is not available either, fortunately ValidationRules.AddRule() can still take string literal.

This might also be helpful is user wants to switch between different sets of valudation rule based on certain instance value.

We could do the same thing to AuthorizationRules which will be more meaningful. Security should definitely be built as a separated common service, instead of building into Domain Object.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s