Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate DTO's for a Client Server application

I've been doing a lot of reading about DTO's recently, having never used them before. One article I read spoke about how DTO's should not just replicate domain model objects but rather each DTO should be tailored to the service operation being performed.

This got me thinking about validation if I decided to used DTO's and wondered if the following would be acceptable?

public class Person {
    public Guid Id {get; set;}
    public string Name {get; set;}
    public Address Address {get; set;}
}

public class Address {
    public Guid Id {get; set;}
    public string AddressLine1 {get;set;}
    ...
}

publuc class CreatePersonDTO {
    private string _name;
    private string _addressLine1;

    public string Name {
        get {
             if (_name == null)
                 throw new Exception("Missing");

             return _name;
        }
        set { _name = value; }
    }

    public string AddressLine1 {
        get { return _addressLine1; }
        set { _addressLine1 = value; }
    }
}

So you pass your data through in either Json or Xml and it is serialised to the object CreatePersonDTO and when mapping those values to create a Person and Address object if the Persons Name is missing then it will throw a validation exception.

As the DTO itself is service operation specific so is having this validation here ok or is it breaking some kind of rule regarding where business logic should reside?

like image 420
David Avatar asked Sep 18 '25 12:09

David


2 Answers

DTOs should have no validation; they are strictly for transferring data. Beyond validation, they should really have no behavior at all.

If the name is required, that is an aspect either of the domain or of a given service operation; validation should be encapsulated in the corresponding places (though you may also enforce the rule in the UI for a better experience).

like image 114
Jay Avatar answered Sep 20 '25 03:09

Jay


I would interpret each DTO should be tailored to the service operation being performed to mean if you have bulky domain objects DTO's can represent a subset that is pertinent to a particular service operation. I.e. it may only be interested in a few properties of the domain object.

like image 20
Yoztastic Avatar answered Sep 20 '25 03:09

Yoztastic