12

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?

gcbs_fln
  • 333
  • 2
  • 10
  • 3
    Some serialisation methods will handle technique A better than B. Of course, nothing stops you doing both (which means do technique B, but also add a public empty parameterless constructor). – mjwills Jun 13 '18 at 13:18
  • I don't know about a "ruling" but many Tools and APIs will fail with private setters . – bommelding Jun 13 '18 at 13:21

2 Answers2

8

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
Alexey.Petriashev
  • 1,634
  • 1
  • 15
  • 19
  • Another con for example A (parameterless constructor) is it is harder to maintain the code when properties are added because the compile (at least the one I use) does not identify the missing property initialization. That is, all properties are optional. – Doug Domeny Feb 08 '22 at 14:20
6

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.

Cool Breeze
  • 1,289
  • 11
  • 34