I need to create some DTO classes to transport our business objects across WCF.
Since these are just bags of data with no functionality, is there any reason I can't just use fields, or is there some good reason to expose them properly as properties?
//fields
[DataContract]
class CustomerDTO
{
[DataMember] public int Id;
[DataMember] public string Name;
}
//or properties?
[DataContract]
class CustomerDTO
{
[DataMember] public int Id { get; set; }
[DataMember] public string Name { get; set; }
}
There is question about DTO (Data Transfer Object) and java implementation with final modifier to fields. In fact. All DTOs must be created in one place (constructor) without any logic inside DTO. If there are several sources - there is aggregation-service, which can collect all data and put it into new DTO.
DTO doesn't have methods. All of the methods that do calculations based on members of DTO are in the dependent class. The more DTOs the dependent class depends on, the more private methods the class has. The more private methods the class has, the harder it is to understand code and write unit tests.
A DTO is an object that defines how the data will be sent over the network. Let's see how that works with the Book entity. In the Models folder, add two DTO classes: C# Copy.
Difference between DTO & Entity: Entity is class mapped to table. Dto is class mapped to "view" layer mostly. What needed to store is entity & which needed to 'show' on web page is DTO.
I mostly favour immutable DTOs with read-only fields if I can get away with it:
public class CustomerDTO
{
public CustomerDTO(int id, string name)
{
Id = id;
Name = name;
}
public readonly int Id;
public readonly string Name;
// Override Equals and GetHashCode as well...
}
There's lots of advantages to be had from immutable records, such as structural equality, which makes automated test assertions much simpler to write. It also dispenses with the need to write and maintain separate Test Data Builders.
It depends on the serializer, though. JSON.NET can handle immutable records, but many other serializers can't.
For those that handle public fields, I prefer fields over properties, simply because it's more honest; automatically implemented read/write properties provide no encapsulation.
Some serializers insist on public properties, and don't serialize fields. If that's the scenario, you have to go with that.
Honestly, considering how much thought I've put into this, it's not really something that keeps me awake at night, because ultimately, at the boundaries, applications aren't object-oriented. Thus, the rules of OOD don't really apply to DTOs anyway.
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