Search code examples
asp.net-mvc-4modelviewmodeldto

From the Model to the DTO to the ViewModel seems just too much


I know a DTO is not a ViewModel. The usage can be the same when its misused but the origion purpose is different.

I return domain entities from my Repository to the Service. In my Service I have to reshape the entities due to the needs of my tabular view.

Now I have a conflict. Normally my service would return a DTO with the data BUT in this case the data is reshaped due to the needs of the presentation layer. Someone could say then the DTO is a ViewModel but I do not want to return a viewmodel from my service.

In this case the DTO is a ViewModel, ok the behavior is missing, but what if there is no further behavior.

Something is wrong here.


Solution

  • It can feel like too much, but don't overlook that it may be just right now that there is an exact match on what you're wanting to generate at the service and UI level. There is nothing inherently wrong about having those two pieces separate but nearly identical.

    Often a ViewModel will be further extended to support computed fields, options for UI selection etc. It will always be easier to extend that distinct object down the road without having to blow up your service (and anyone who's taken a dependency on it).

    On the other hand, I really like to follow YAGNI. So, if you honestly believe there is no way this object is likely to grow, recycling something isn't always terrible. (More context would definitely help to make this call).

    Finally, don't spend so much time on the academics of it. You seem to have a pretty good handle on what you're trying to accomplish, and the only good code is shipped code. Write tests, separate what you can, but get the code out the door. I've seen projects fail because of over-engineering.

    Cheers.