Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Domain vs DTO vs ViewModel - How and When to use them?

In a Multi-layer project with Domain layer (DL)/Business (Service) Layer (BL)/Presentation Layer (PL), what is the best approach to deliver Entities to the Presentation Layer?

DO => Domain Object; DTO = Domain Transfer Object; VM => View Model; V => View; 

Option 1:

DL => DO => BL => DTO => PL => VM => V 

This option seems to be the Best Practice but also seems heavy to mantain.

Option 2:

DL => DO => BL => DTO => PL => V 

This option seems not very good practice but as DTO are almost identical to the VM, we can pass it directly to the View and it's less painfull to implement and mantain.

Is this option also reliable for multiple layouts, for example, for Mobile Devices I may need less information from the BL, so I will need a diferent VM for this particular Layout?

like image 453
Patrick Avatar asked Oct 13 '12 15:10

Patrick


People also ask

What is the difference between DTO and ViewModel?

The purpose is different: DTO's are used to transfer data. ViewModels are used to show data to an end user.

Is a DTO a domain object?

If using anemic data model (i.e. your domain objects don't have any logic), DTO and domain object can be the same object. No. Domain objects have no specific relation to any persistence. In simple words, they are parts to ensure the business logic required to run the application.

Is DTO a model in MVC?

MVC Model Object and Domain Object both are same. 3) If there is no business logic in Domain Object then automatically it becomes DTO.

Why do we use ViewModel?

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.


Video Answer


2 Answers

It's OK to pass the DTO to the view. If you need to change or enhance the DTO then create a ViewModel. A common scenario would be to add links. It's also OK for the ViewModel to reference the DTO as a complex property.

like image 143
Max Toro Avatar answered Oct 03 '22 08:10

Max Toro


If you are going to have different views that require different data from your Dto it sounds like you might benefit from having different view models for these and map your Dto to these.

One of the ideas behind this is to allow greater freedom to change your view model, knowing it will not have an impact on any other part of your application. If your Dto is being used in several views then each change to your Dto would require you to test each view.

like image 20
dove Avatar answered Oct 03 '22 09:10

dove