Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the single responsibility principle mean for validation

Does the single responsibility principle mean that your validation rules should be external to the entity?

If so do you use one class per validation rule?

like image 928
Dug Avatar asked May 14 '09 19:05

Dug


People also ask

What is the Single Responsibility Principle imply?

The Single Responsibility Principle (SRP) The idea behind the SRP is that every class, module, or function in a program should have one responsibility/purpose in a program. As a commonly used definition, "every class should have only one reason to change".

What is the Single Responsibility Principle and how does it apply to components?

As the name suggests, this principle states that each class should have one responsibility, one single purpose. This means that a class will do only one job, which leads us to conclude it should have only one reason to change.

Why is Single Responsibility Principle important?

The argument for the single responsibility principle is relatively simple: it makes your software easier to implement and prevents unexpected side-effects of future changes.

What is Single Responsibility Principle in agile?

Definition: An object should have a single responsibility. This means that a class should only have one reason to change. An example of how this might work is with a class that compiles and formats a report. This class has two responsibilities and two reasons the class might change.


1 Answers

I would normally interpret this to mean that en "entity" and the validation of an entity should be separate concerns. I would normally use a single class that can validate an entire entity, but I would see no reason to constrain its implementation by not letting that class use other classes. But I would not split validation of an entity into multiple classes just because the entity has multiple attributes; I would define the responsibility of the validator as "validate entity X". Sometimes single responsibility just boils down to defining a responsibility in a clever way, and it's really about you making the rules.

Sometimes you can come across entities that have multiple valid states that may be at a different phase of a process; an order may have separate validators for separate phases, but I consider that to be a different responsibility for each validator.

like image 50
krosenvold Avatar answered Sep 28 '22 05:09

krosenvold