DEV Community

Discussion on: Data Validation: Scratching Surface of Code Responsibility

Collapse
 
oberonus profile image
Alexander Demin

Hey, thanks for the feedback. I agree that "do I need external information to perform this validation?" question is actually the one that should give information about logic placement. Bounds checking is a place when it becomes a bit tricky.

For example, in provided example - user age. Does the infra layer have enough information to validate it? It can check basic contract requirements, e.g. this field should be in age field of JSON payload, it should be integer and it must be provided. But the check of actual age - here when it falls into domain layer, since infra layer does not have enough information (and should not) - what age is allowed? Is it 18-60? or 18-110? or 21-110? This validation highly depends on the domain rules and can't be placed in infra layer (system boundary) without domain logic leak.

Collapse
 
rytheturtle profile image
RyTheTurtle

That's a great point, and I agree the domain logic should not leak in to the system boundary / infra layer.

In my experience, the answer is that any particular field or validation doesn't have to exclusively be validated in one part or another. To take the same example, my answer would be two fold:

  • infra layer: Validate the age is present and is a positive integer.
  • domain layer: Validate the domain-specific rules for allowed ages for users.
Thread Thread
 
oberonus profile image
Alexander Demin

Yes, 100% agree. The main point is that this is a question of code responsibility. It is not about specific fields, but more about the validation scope that can be done in specific place while still having strong boundaries between layers.

Some pieces of validation can be even duplicated, e.g. domain logic can be called not from infra, but from another domain service, and proper validation still should be applied. So here is the question - what can/should be placed in infra layer and for what reason -IMO it is almost always a question of optimization.