Return DTO or Model?
I’m a junior developer and started my first job as a developer and have a question regarding DTO and Model.
Consider this code snippet
@Override
public ResponseEntity<List<PostalCodeLocationModel>> findPostcalCodeLocationPairs(final PostalCodeLocationSearchModel model) {
final String postalCode= model.getPostalCode();
final String location = model.getLocation();
final List<PostalCodeLocationModel> listOfPostalCodeLocationPairs = service.findPostalCodeLocationPairs(plz, ort).stream()
.map(mapper::dtoToModel)
.toList();
return ResponseEntity.ok(listOfPostalCodeLocationPairs);
}
A similar approach is used in the project I am working on. I am a bit confused because what I have learned is, that in this layer where the Controller is, always map to DTO in the end and send the DTO but here, the service is returning a DTO which is then mapped to the model and return. Is this approach correct?
This is a common question and the answer is
The purpose of DTO is that your controller returns an object in your API that is separate from your core entities.
If you have a core entity called Transaction that contains an object of type Currency, it is a bad practice to return Transaction and leak to the outside that your transaction has a type Currency in it, instead you create a DTO and in the DTO format the currency to a String, this way your entities preserved and hidden from what your controller returns. Now your API and core entities can change independently without breaking each other.
The correct order is that services will return model entities, and in your controller, they are mapped to a DTO.
✨ Enjoyed this post? If you found this content valuable, don’t forget to clap to show your support! Your claps help others discover these insights.
🔔 Want to stay updated? Hit that follow button to never miss out on my latest posts and updates. Join our community and be part of the conversation!
Thanks for your support and engagement! 🙌
Return DTO or Model? was originally published in Javarevisited on Medium, where people are continuing the conversation by highlighting and responding to this story.
This post first appeared on Read More