Tools and Patterns for Business Rules in C#

cdomain-driven-design

I am looking at Fluent Validation for my rich domain model: https://github.com/JeremySkinner/FluentValidation

Lets say I have a class called: Customer. The Customer must have a surname. I can do this:

RuleFor(customer => customer.Surname).NotEmpty();

I can do something similar to make sure they are over a certain age etc. Now lets say I want to provide offers to a customer who is between the ages of 18 and 25. Is this something I should be doing using the Fluent API? If not then is there another tool/pattern that I should be using?

All as I need to do is return a message if the person is between those ages i.e. you are entitled to the following offers: x,y, and z". Please note this is for one customer rather than a collection of customers.

Is it normal to test domain rules using Fluent API? For example, if user is between 18-25, then show them this offer (string); if they are 25-40 then show them this offer etc. These are not validation errors i.e. it is perfectly reasonable for someone to be 25 years old or 40 years old etc.

Best Answer

I'd make a ValidationProvider class that'll get your validators on demand, given any domain state.

like:

public class UserValidatorProvider
{
    public static IValidator GetValidator(User user)
    {
        if(user.Age > 40){
            return validator1;//you'd probably use the fluent api here
        }else{
            return validator2;//or maybe encapsulate that fluent in a ctor of a class like new UserOver40Validator()
        }
    }
}

That is, a Domain has a State (like, the user is over 40), given a State select a Validator.

You'd have to swap validators at runtime.

As for where to put them in the layers, you will have different validation procedures for each use case at all layers necessary. That is, UI feedback, Business Rules, Domain Validation, but only where needed.

I think it's that simple!

Related Topic