13

I want to place validation in one layer for the reason of simple code maintenance. I was thinking of entity validation, cause this protects directly database. Am I right, or should I add validation also on dto level? I would be happy, if someone share his experience on the topic.

Bartek
  • 241
  • 1
  • 2
  • 5

2 Answers2

18

Without knowing what you mean by DTO or Entity, I'm going to make some assumptions, and then I can answer.

  • DTO — An object that represents data passed to the server from the client
  • Entity — A business logic class mapped to a persistent data store

Entities should perform validation. And you should validate the DTOs. The difference lies in what happens when invalid data is encountered.

If invalid data is passed to an Entity's methods, or you try to initialize a new entity with invalid state, the Entity itself should throw exceptions. A validation failure that isn't caught should crash the thread.

DTOs can and should be passed invalid data, and initialized with invalid state. Another set of classes should look at the current state of the DTOs to ensure that passing this information down to your Entities will not cause exceptions to be thrown. Detecting a failed validation rule should not crash the application, and instead should push a message into a collection that will eventually be shown to the end user where they will be given a chance to correct their data and attempt the business operation again.

Validating the DTOs is tantamount to performing pre-checks on the data before initializing new Entities, or calling methods on existing Entities ensuring business rules are being followed prior to the execution of those rules.

Greg Burghardt
  • 34,276
  • 8
  • 63
  • 114
3

Each layer should have own validations. For example, Business Logic Layer(BLL) and Data Access Layer(DAL) should have own validations.

Beyond this, assume that you call the BLL via network. Then, you can check some input validations or something else before send request to server in order to reduce network traffic. But it doesn't mean you can remove validation from BLL or DAL.

Shortly, adding extra validations in order to improve performance and/or saving resources is good approach but layers validations should exist.

Engineert
  • 917
  • 1
  • 5
  • 17
  • 2
    You bring up a good point too, looking beyond just "entities" and DTOs. +1 for recommending that each layer should have their own validations. This is especially useful when the stack trace for a thrown exception originates in library code deep in someone else's framework. Stack traces from your own code are much easier to debug than some random SocketConnection thrown from library code connecting to a remote resource. – Greg Burghardt Feb 28 '19 at 12:26