Search code examples
asp.netdesign-patternsweb-applicationsdto

Strategy for DTO pattern - multiple DTOs per entity or just one?


I'm building my first application with DTOs - I currently have one DTO for GETting data for a particular object, and another different DTO for updating (PUTting) data - since only a few fields can ever possibly be updated from any client, I decided to create a dedicated DTO for PUTting to avoid sending unnecessary data/fields over the wire. Is this good practice in terms of maintainability, or is this some kind of no-no?


Solution

  • I have no problem with using the same type for multiple operations. Perhaps you have multiple GETs which return similar data for similar purposes. There's no reason you can't reuse the same type in that scenario.

    However, you've identified that your GET and PUT operations require different data. So not only are they different operations, but they also need different data.

    +----------------+-------------------+--------------------------+
    | Similar Data   | Similar Purpose   | Try to Reuse             |
    | Similar Data   | Different Purpose | Consider; is it logical? |
    | Different Data | Similar Purpose   | New Type                 |
    | Different Data | Different Purpose | New Type                 |
    +----------------+-------------------+--------------------------+
    

    There are other benefits to creating a new DTO to meet the specific need, such as:

    • not confusing the developer (even if that's you!)
    • not opening a security hole whereby fields not intended to be used are populated

    To make it easier:

    • interfaces can be used to help enforce common fields between types.
    • ASP.Net Web API (not sure if you are using from your question) has strong support for dynamic inputs. This can eliminate the need for DTOs (albeit at the expense of less compile-time type checking).