简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM