Yesterday I was developing a small ecommerce web application using spring framework. I was watching a tutorial and the educator created a package called dto. I haven’t seen that before.
He created a Product class in the model package. and he also created a ProductDTO class in the dto package. Both the classes has almost same fields. I was confused. Then I started looking on medium why to use a DTO. This is what I learnt.
What is a DTO?
DTO stands for Data Transfer Object. It acts as a class with no business logic. As the name specifies, It is used to transfer data from one part(layer) of the application to other.
It is a simplified version of the model class. The only purpose of DTO is to act as an object that contains the necessary data that can be passed to different layers of the application. Or it can be used to pass the data between several microservices.
Example
Lets look at the difference between a model and a DTO.
Consider a model Product. It contains four fields. id, name, category, price. This class can be a JPA entity.
public class Product {
int id;
String name;
Category cat;
double price;
}
The DTO of above class looks like:
public class ProductDTO {
int id;
String name;
id cat_id;
double price;
}
Here, Category is a model containing the category details like id, name. In productDTO, the actual category is not needed because storing the id of category is enough when passing the DTO from one of the layer to another.
DTO should contain following properties:
Immutable
As it is a data object, it should be immutable.
Serializable
A DTO’s main purpose is to transfer the data from one object to another, it should be serializable.
Efficient
A DTO should be efficient i.e. it shouldn’t contain any unnecessary data. In the above example, instead of using Category object, we use category id in the DTO. It will improve the performance of the application. In some cases, the presentation layer doesn’t need all the product data. So, DTO should be minimal.
Note: The above article may contain mistakes. I am a beginner and I am sharing what I have learnt. So, Your feedback can be helpful.
Thanks for reading.
💗 If you like my content, Clap this article, Follow me and You can buy me a coffee at BuyMeACoffee ☕