DTO: Hipster or Deprecated?
DTO: Hipster or Deprecated?
The purpose of this article is to talk a little bit about the usefulness of DTO and address this question.
Join the DZone community and get the full member experience.Join For Free
Data Transfer Objects, known affectionately as DTOs, is the subject of a lot of discussions when we talk about the development of Java applications. DTOs were born in the Java world in EJB 2 for two purposes.
First, to circumvent the EJB serialization problem; second, they implicitly define an assembly phase where all data that will be used for presentation is marshaled before actually going to the presentation layer. Since the EJB is no longer used on a large scale, can DTOs also be discarded? The purpose of this article is to talk a little bit about the usefulness of DTO and address this question.
After all, in an environment of several new topics, (for example, cloud and microservices) does this layer even make sense? When it comes to good software architecture, the answer is practically unanimous: It depends on how closely you want your entity to be coupled to the visualization layer.
Thinking about an underlying architecture in layers, and dividing into three interconnected parts in itself, we have the famous MVC.
It is worth noting that this strategy is not exclusive to the stack of web applications like Spring MVC and JSF., Exposing your data in a restful application with JSON, The JSON data works as a visualization, even if it is not friendly to a typical user.
Once MVC is briefly explained, we will talk about the advantages and disadvantages of using DTO. Thinking of layered applications, DTO, above all, has the objective of separating the model from the view. Thinking about the problems of DTO:
- Increases the complexity
- There is the possibility of duplicate code
- Adding a new layer has the impact of the delay layer, that is, the possible loss of performance.
In simple systems that do not need a rich model as a premise, not using DTO ends upbringing great benefits to the application. The interesting point is that many serialization frameworks end up forcing the attributes to have accessor or getter and setter methods that are always present and public as mandatory, so, at some point, this will have an impact on application encapsulation and security.
The other option is to add the DTO layer, which basically guarantees the decoupling of the view and the model, as mentioned previously.
It makes it explicit which fields will go to the view layer. Yes, there are several annotations in various frameworks that indicate which fields will not be displayed. However, if you forget to write down, you can export a critical field accidentally, for example, the user's password.
Facilitates drawing in object orientation. One of the points clean code makes clear about object orientation is that OOP hides the data to expose the behavior, and the encapsulation helps with that.
Facilitates updating the database. It is often essential to refactor, migrate the database without this change impacting the customer. This separation facilitates optimizations, modifications to the database without affecting the visualization.
Versioning, backward compatibility is an important point, especially when you have an API for public use and with multiple customers, so it is possible to have a DTO for each version and evolve the business model without worry.
Another benefit is found in the ease of working with the rich model and in the creation of an API that is bullet approved. For example, within my model, I can use a money API; however, within my visualization layer, I export as a simple object with only the monetary value for visualization. That is the right old String in Java.
CQRS. Yes, is Command Query Responsibility Segregation about separating responsibility for writing and reading data and how to do this without DTOs?
In general, adding a layer means decoupling and facilitating maintenance at the expense of adding more classes and complexity, since we also have to think about the conversion operation between these layers. This is the reason, for example, of the existence of MVC, so it is very important to understand that everything is based on impact and trade-offs or what hurts in a given application or situation.
The absence of these layers is very bad, it can result in a Highlander pattern (there can be only one) of which there is a class with all the responsibilities. In the same way, the excess layers become the onion pattern, where the developer cries when passing through each layer.
A more frequent criticism within the DTOs is at work to perform the conversion. The good news is that there are several conversion frameworks, that is, it is not necessary to make the change manually. In this article, we will choose one that is the modelmapper.
The first step is to define the project's dependencies, for example, in Maven:
To illustrate this concept of DTO, we will create an application using JAX-RS connected to MongoDB, all these thanks to Jakarta EE, using Payara as a server. We manage a user with username, salary, birthday, and list of languages the user can speak. As we will work with MongoDB in Jakarta EE, we will use Jakarta NoSQL.
In general, it makes no sense to have entities have getters and setters for all attributes; after all, that would be the same as leaving the attribute public directly. Since the focus of our article is not on the DDD or rich models, we will omit the details of that entity. For our DTO, we will have all the fields that the entity has; however, for visualization, our 'MonetaryAmount' will be a 'String', and the anniversary date will follow the same line.
The great benefit of the mapper is that we don't have to worry about doing this manually. The only point to note is that particular types, for example, the Money-API's 'MonetaryAmount', will need to create a convert to become 'String' and vice versa.
The converters are ready; our next step is to instantiate the class that performs the 'ModelMapper' conversion, a big point of using dependency injection is that we can define it as the application level. From now on, the entire application can use the same mapper; for that, it is only necessary to use the annotation 'Inject' as we will see ahead.
One of the significant advantages of using Jakarta NoSQL is its ease of integrating the database. For example, in this article, we will use the concept of a repository from which we will create an interface for which Jakarta NoSQL will take care of this implementation.
In the last step, we will make our appeal with JAX-RS. The critical point is that the data exposure will all be done from the DTO; that is, it is possible to carry out any modification within the entity without the customer knowing, thanks to the DTO. As mentioned, the mapper was injected, and the 'map' method greatly facilitates this integration between the DTO and the entity without much code for that.
Managing databases, code, and integrations is always hard, even on the cloud. Indeed, the server is still there, and someone needs to watch it, run installations and backups, and maintain health in general. The twelve-factor APP requires a strict separation of config from code.
Thankfully, Platform.sh provides a PaaS that manages services, such as databases and message queues, with support for several languages, including Java. Everything is built on the concept of Infrastructure as Code (IaC), managing and provisioning services through YAML files.
In previous posts, we mentioned how this is done on Platform.sh primarily with three files:
1) One to define the services used by the applications (services.yaml).
2) One to define public routes (routes.yaml).
It's important to stress that the routes are for applications that we want to share publicly. Therefore, if we want the client to only access these microservices, we can remove their access to the conferences, sessions, and speakers from the routes.yaml file.
3) Platform.sh makes configuring single applications and microservices simple with the '.platform.app.yaml' file. Unlike single applications, each microservice application will have its own directory in the project root and its own '.platform.app.yaml' file associated with that single application. Each application will describe its language and the services it will connect to. Since the client application will coordinate each of the microservices of our application, it will specify those connections using the 'relationships' block of its '.platform.app.yaml' file.
In this presentation, we talked about integrating an application with the DTO, in addition to the tools to deliver and map your DTO with your entity in a straightforward way. We also covered the advantages and disadvantages of this layer.
Opinions expressed by DZone contributors are their own.