❔ Avoiding duplicating code between DB models and DTOs
Hi there. I don't know if "DTO" is the right word to describe what I'm talking about, but...
I have a Discord bot which is also hosting an API to allow other bots/platforms/applications to interact with the bot for some features in a TOS-abiding way. At the present moment, my DB models also have logic attached to them, which I plan to separate in some way to keep the models themselves tidy and readable.
I've been told it's not a best practice to return/serve DB models directly as JSON in API calls, so I am looking to avoid doing that via, what I believe would be DTOs. How do I avoid the unnecessary code duplication in what would effectively be a copy of the model class(es) in the API? My main concern is, even if I couldn't avoid it, any changes to DB models would require me to remember to make an identical modification where appropriate to the API DTOs. This is not something I'd prefer as my current setup already suffers from that issue.
Any suggestions or ideas are welcome. At the moment, I don't see a huge need for DTOs on my bot side of things as I'd be doing the data manipulation behind the scenes and Discord bots don't exactly return data like APIs do...but I do have some pretty complicated logic attached to the current models that I'd either have to extract as extension methods or DTOs...for a second time (bot DTOs / API DTOs)
9 Replies
There will be duplication, and it will be worth it.
Yep
Duplication is preferable to returning raw db entities
The two classes serve two different purposes. DTOs describe what you're sending to the client, and DAOs (data access objects, your EF entities) describe what you're sending to/receiving from the database.
so then the answer to
How do I avoid the unnecessary code duplication in what would effectively be a copy of the model class(es) in the API? My main concern is, even if I couldn't avoid it, any changes to DB models would require me to remember to make an identical modification where appropriate to the API DTOs. This is not something I'd prefer as my current setup already suffers from that issue.is just "remember to make the changes idiot"?
While those things are obviously going to be very similar and possibly identical, the classes still represent two different things.
yep lol
then
In my experience it's not too hard to remember, especially if you use
required
on your DTOs.
Then if you add a new property to a DTO, wherever that DTO is created will now have a compiler error until you fill in the blank.
Though at the end of the day you should notice when you test to make sure your changes worked either way.If you forget to reflect some DAO changes in the DTO... that means it wasn't needed in the DTO
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.