Data Transfer Object (DTOs) and ViewModels
There are many different naming conventions used in the web development space. While most of them range from private vs. public variables and what casing to use, there are few that are more involved and tell the programmer more information about what a construct is used for. In .NET web development, DTOs and ViewModel postfix naming conventions are two examples of naming that give you more descriptive information. Take a DTO for example:
public class ArticleInfoDto { public string Id { get; } public string Category { get; private set; } public int Duration { get; private set; } public string ExpirationDate { get; private set; } }
And the same if used as a View Model:
public class ArticleInfoViewModel { public string Id { get; } public string Category { get; private set; } public int Duration { get; private set; } public string ExpirationDate { get; private set; } }
DTO stands for “Data Transfer Object”, and implies that it is a serializable entity that is to be transferred between systems. This immediately gives valuable information to the developer. One thing it tells the developer is to be careful removing elements from this object, as an external system may depend on the field. Even if the code compiles, run time errors or erroneous behavior may occur at run time because of the transfer of data across the wire. Another benefit of DTOs is it allows modifications to be done on the domain model (in domain driven development) without impacting external systems. As an example, lets say the domain model of an article needs the Duration to be in hours instead of minutes. We now can convert the model without changing the DTO of the external object, so the external system would not be affected, and logic would just have to be made with translation or adapter logic.
New Article Domain Model Class:
public class ArticleInfo { public string Id { get; } public string Type { get; private set; } public string Hours { get; private set; } public string Category { get; private set; } public int Duration { get; private set; } public string ExpirationDate { get; private set; } }
New initialization of DTO to be transferred to an external system:
Var articleInfoDto = new ArticleInfo { Id = article.Id, Type = article.Type, Hours = article.Hours, Category = article.Category, Duration = article.Duration * 60, //convert from domain model to existing DTO ExpirationDate = }
ViewModels are similar to DTOs in that are made to go over the wire (as in the case if you are using a Javascript framework or library). They are another construct that is derived from the domain model but has been modified to fit the requirements of an external system. In the case of View models, the external system is actually an internal subsystem that is in charge of displaying the data in a UI.