Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use service layer or IValidatableObject

I would like to know what is the best way to validate a model before saving it and the pros and cons. I'm in doubt between service layer and IValidatableObject.

Service layer:

public class PersonService
{
    public void Insert(Person person)
    {
        if (!IsValid(person))
        {
            //something
        }
    }
}

IValidatableObject:

public class Person:IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!IsValid(this))
        {
            //something
        }
    }
}
like image 580
MuriloKunze Avatar asked Dec 20 '22 15:12

MuriloKunze


1 Answers

IValidatableObject is typically used to self-validate the entity, i.e. validation is restricted to checking the properties of Person.

Self validation (e.g. IValidatableObject and DataAnnotations) are useful for the 'initial' checking, e.g. on user interfaces, to ensure that a user has filled in all required fields, and broadly meets validation rules like regex matches, string lengths, date ranges etc.

In order to keep your Person entity decoupled from the rest of your system, you wouldn't be able to do more advanced business rules in Self Validation which required round trips to your database, or used service calls to external systems.

In contrast, validation done on a Service / Business / Manager Layer is usually used as part of a transaction, e.g. Inserting / Updating / State Transitions, and this can do more involved validation, e.g.

  • It can check additional Business Rules, which do require information not immediately available in the Person entity (i.e. fetch related data from the database, consume other web services etc, when making validation decisions). An example here would be to determine whether a bank account has any funds available, or whether more than 10 withdrawals were made in a day.
  • Validation of state-specific rules, e.g. Different rules may be applied when inserting or updating a person, or different rules may be applicable if the person is alive or dead. This additional context may not be available with Self Validation.
  • However, service / business tier checking can still make use of Self Validation (e.g. person.Validate()) (including using IValidatableObject) to prevent duplicating rules.
like image 176
StuartLC Avatar answered Jan 24 '23 14:01

StuartLC