Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a DTO/POCO have a constructor and private setters on all properties?

I know there are many discussions here about DTOs and POCOs, but I couldn't really find one about this. Is there a rule on writing DTOs without constructors vs private setters and constructors?

Example A:

public class Person
{
    public int Id { get; set; }
    public String Name { get; set; }
    public int Age { get; set; }
}

Example B:

public class Person
{
    public Person (int id, String name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
     }

    public int Id { get; }
    public String Name { get; }
    public int Age { get; }
}

Is any of the two approaches considered anti-pattern? Why? I mean, I know one could argue in favor of immutability or boiler platting and refactoring issues, but is there a de facto approach, something official?

like image 521
gcbs_fln Avatar asked Jun 13 '18 13:06

gcbs_fln


People also ask

Does a DTO have a constructor?

A DTOs Structure. Data Transfer Objects are public (static) classes with no methods, other than the compiler supplied default constructor, having only public fields limited to the easily serializable types: i.e. A DTO is equivalent to a struct in C.

Should DTO be immutable?

The aim of a DTO is to carry data between processes. It is initialized, and then, its state should not evolve. Either it will be serialized to JSON, or it will be used by a client. This makes immutability a natural fit.

Should DTOs have methods?

A data transfer object (DTO) is a collection of public fields. If there are any methods, they are constructors for quickly making the DTO. DTOs do NOT contain logic. DTOs are often used with a form of data mapper called a DTO assembler.

Is POCO a DTO?

Most importantly it is a well established fact that DTO is NOT a POCO. DTO is a data container, while POCO are objects as properties and are persistence ignorant (no get or save methods).


2 Answers

DTO should not be immutable bacause the main purpose is to be serializable and deserializable. So immutability does not matter.

But

  1. You need to mark DTO as DTO... For example add postfix DTO (PersonDTO)
  2. You must be sure that you dont use DTOs in any logic. After receiving DTOs should be converted to Domain objects

Mutable pro

  • easy constructable
  • easy serializable

Mutable cons

  • can be changed by mistake...

Immutable pro

  • can not be changed by mistake...

Immutable cons

  • sometimes hard to construct
  • can have problems with serializers
like image 168
Alexey.Petriashev Avatar answered Oct 04 '22 09:10

Alexey.Petriashev


Example B is better because it is immutable. The purpose of a DTO is to transfer data so there is no need for the data to change.

like image 44
Cool Breeze Avatar answered Oct 04 '22 08:10

Cool Breeze