DTO vs View Model

Recently, I delivered a project that had both DTO, (Data Transport Object) and a View Model or dozen. I got the question on why we had them. Because my implementation was as much about demonstrating more advanced programming concepts to a shop with a history a large scale code behind programming. By design the GUI and the data layer were intermixed in their existing system. That being one problem, the may goal of my project was to deliver a division between the data access, business rules and GUI layers of a project. One of those things that allow the decoupling are the use of DTO and View Models. Lets dig into the similarities of difference between a DTO and a View Model.

What Do a DTO and View Model Have in Common?

First both are responsible for moving data. They have no logic. They have no brain. That super neat function that you thing should be in them. It should not. Nope they both have no logic in them. There sole purpose is to move the data from one layer to another.

If The Are So Alike, Why Are They Different?

The primary difference is the purpose of the data they are shoving between the layers. A DTO job is to reduce the number of calls between the data layer and the business layer. In a simple system, like I delivered to my clients, it is pretty close to a one to one match. They have a client table, they insert client. That case is not always the reality. A good example of this is if you want to accept a client registration and an address. Presumably, we have a client table and an address table. The address table has a key to the client table. Now without a DTO, you make a call to save the client and then another to call the address. On a big system that is extra overhead you don’t need. You can merge them together and let the data layer figure out the saving mechanics and leave the business rules happy to just apply whatever controls it wants to add.

A View Model job is different. Like the name implies this is the view’s model. We want to use a view model to limit the data down to what the view needs delivered by its controller or presenter. We use it to prevent exposing and sending data that is not needed to the view. Hopefully making the view more responsive.

At least that is the practical definitions that I was taught and encouraged to use. If it’s true, I’m sure there are some knowledgeable folks that will give me hell in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *