Search code examples
c#asp.net-mvcasp.net-web-apiviewmodeldto

DTO vs VM - To use or not to use?


In asp.net (webapi+mvc) project i have many dto as public interfaces to my BLL. Also, most of my view models are same to appropriate dtos.

Smart books tell us that we have to separate this kind of models, but on the project i see no benefits of this solution. Only hundreds of useless code with many stupid mistakes.

So - is it correct to use DTO as a view model where it is possible? What are the positive and negative effects of this solution?


Solution

  • A data-transfer object is just a subset or superset of data to be transferred between logical and physical boundaries. They can't provide behavior. They're just data.

    In the opposite side, a view model is a mix of data and behavior since they're the logical side of a given view.

    Since DTO and VM are patterns that cover different use cases, you can end up with useless data and behavior, and you can add unwanted dependencies.

    For example, a DTO can be used both in the domain and application layers. If you're using both DTO and VM concepts materialized in a single class, you can end up forcing a domain project to add a reference to an UI library to be able to build it. I would avoid this as much as possible.

    In addition, you know there's an object-oriented concept called inheritance, which can assist you here in order to stay DRY (don't repeat yourself):

    public class Base {}
    
    public class Dto : Base {}
    public class ViewModel : Base {} 
    

    In summary, you can share what's common to both DTO and view models with inheritance and avoid code repetition.