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?
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.
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.
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.
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).
DTO should not be immutable bacause the main purpose is to be serializable and deserializable. So immutability does not matter.
But
Mutable pro
Mutable cons
Immutable pro
Immutable cons
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With