DTOS. Properties or fields?

I need to create some DTO classes to transfer our business objects to WCF.

Since these are just data bags without any functionality, is there any reason why I cannot just use the fields, or is there some good reason for them to display correctly 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; } } 
+7
source share
4 answers

Since these are just data bags without any functions, is there any reason why I cannot just use fields

There are no compelling arguments against public fields. But keep in mind that only because there is no logic (behavior) inside the DTO, so the normal encapsulation argument is not executed.

I would still prefer properties, but they are not needed here.

+4
source

The DataMember will work with both shared fields and properties, so that would be possible. However, I would recommend sticking with properties.

In particular, if you use StyleCop, then you break the rule SA1401 .

The reason for the existence of this rule does not really apply in your case, but it will still be a maintenance problem if you use StyleCop authentication as part of the assembly on the continuous integration server.

+2
source

You can also use. Since this does not affect performance, you can be safer with respect to properties if you come across any serialization scheme or similar that does not work with public fields.

Note that WCF proxy generation will create these client-side DTOs with public properties and their private security fields, even if you use public fields on the service side. If you somehow do not want this, you need to split the DTO library between the service and the client.

+1
source

I will never disclose the fields directly; most companies prohibit this in their standards. Effectively, you completely throw away encapsulation. DTOs, being anemic representations of something more complex, are a strange case, since their properties largely violate encapsulation. Personally, I would use properties as what they are for. It also allows you to implement "dirty" functionality, etc., if you need it, which is not so simple if you configure the fields directly.

0
source

All Articles