What is the general idea to help deciding when to use DTO and when to use Entity in these cases ?
I like reading the code that pass entities around :
But there are arguments about DTO that maps to an entity is safer, because it's a contract, and the entity can change to whatever form, and the DTO will stay the same. For example, like the entity has a field name, and the DTO also has a field name. Later on, if the requirement changes, the database table changes, the entity can change also, changing name into firstName and lastName. But the DTO will still have a field name, which is firstName + lastName.
So here's the list of the pros of using DTOs :
The cons of DTO i can think of is :
Please share you thoughts ..
Thank you !
Here are some quotes from different places
pro dto :
Reuse of the entity class as a DTO seems messy. The public API of the class (including annotations on public methods) no longer clearly defines the purpose of the contract it is presenting. The class will end up with methods that are only relevant when the class is being used as a DTO and some methods that will only be relevant when the class is being used as an entity. Concerns will not be cleanly separated and things will be more tightly coupled. To me that is a more important design consideration then trying to save on the number of class files created.
Absolutely NOT!!!
JPA entities are mapped to a database, but they are not 'tied' to a database. If the database changes, you change the mappings, not the objects. The objects stay the same. That's the whole point!
I would go for the DTO option for the following reasons: