Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to effectively use DTO objects (Data Transfer Objects)?

What is the best way to implement DTOs?

My understanding is that they are one way to transfer data between objects. For example, in an ASP.Net app, you might use a DTO to send data from the code-behind to the business logic layer component.

What about other options, like just sending the data as method parameters? (Would this be easiest in asces wher there is less data to send?)

What about a static class that just holds data, that can be referenced by other objects (a kind of global asembly data storage class)? (Does this break encapsulation too much?)

What about a single generic DTO used for every transfer? It may be a bit more trouble to use, but reduces the number of classes needed to work with (reduces object clutter).

Thanks for sharing your thoughts.

like image 635
alchemical Avatar asked Sep 02 '26 12:09

alchemical


2 Answers

I've used DTO's to:

  • Pass data between the UI and service tier's of a standard 3-tier app.
  • Pass data as method parameters to encapsulate a large number (5+) of parameters.

The 'one DTO to rule them all' approach could get messy, best bet is to go with specific DTO's for each feature/feature group, taking care to name them so they're easy to match between the features they're used in.

I've never seen static DTO's in the way you mention and would hesitate at creating DTO singletons like you describe.

like image 152
Mike Reedell Avatar answered Sep 05 '26 15:09

Mike Reedell


I keep it simple and map one DTO class to one db table. They are lightweight so I can send them everywhere, including over the wire.

like image 22
Otávio Décio Avatar answered Sep 05 '26 17:09

Otávio Décio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!