PacktPublishing / Software-Architecture-with-C-9-and-.NET-5

Code Repository created for Hands-On Software Architecture with C# 9 and .NET 5, Published by Packt
MIT License
39 stars 36 forks source link

making DTO class to be a record (C# 9.0) #20

Open shahabfar opened 3 years ago

shahabfar commented 3 years ago

In theory, anywhere that you have a class that holds information and is immutable, you should seriously consider making it a record. While the book is about C# 9.0 it is better the features of C# 9.0 be considered in examples of the book. The CTO class used in chapter 8 is a good candidate to be changed to record.

frankabbruzzese commented 3 years ago

It depends on the context. The code in the chapter 8 example is just a small part of an application so one can't decide this based just on that code fragment. Everything depends on the intended usage of that class in the overall application.

Anyway, being implemented as a record or not is more a matter of how equality is handled than a matter of being immutable or not. Immutability is translated with {get; init;} properties, while records are characterized by how equality works for them.

For sure Value Objects (see chapter 12), such as an Address should be implemented as a record, as suggested in the book since they have no identity and behave like structures.

For what concern query results that do not represent value objects, it depends on if you are using or not the CQRS pattern (see chapter 12). If you are not using CQRS and if the DTO has a property that works as a key it should not be implemented as a record since records have no identity. However, if the DTO has the only purpose of returning a query item, it should be read-only and it should be defined as immutable (all properties should be {get; init}).

In chapter 8, probably that DTO might be defined as immutable, but this depends on if the query results are editable or not, which is not clear from the code snippets in the examples.

On the other side, if one is using CQRS, query results must never be editable and have record semantics also if they contain some key properties. As a matter of fact, a query result might contain the key properties of several objects or of no object, they are just lists of name-value pairs.

shahabfar commented 3 years ago

Thanks for your comments