5 Rules For DTOs

Поделиться
HTML-код
  • Опубликовано: 3 апр 2024
  • 5 Rules for (better) DTOs
    Hey everyone, I'm Steve Smith aka ardalis, of NimblePros!
    In this video I'm going to tell you how to write better DTOs using 5 simple rules!
    Let me know what you think or share your own tips in the comments below!
    Get the Code
    You can request the code used in this video here:
    mailchi.mp/ardalis.com/5tipsdtos
    Links
    ardalis.com/dto-or-poco/
    ardalis.com/web-api-dto-consi...
    Check out my courses:
    dometrain.com/course/getting-...
    dometrain.com/course/deep-div...
    ardalis.com/training-classes/
    www.pluralsight.com/authors/s...
    Team Consulting and Training: NimblePros.com and @nimblepros
    Developer Group Mentoring: devBetter.com
    Free Weekly Email Tips:
    ardalis.com/tips/
    If you read this far, I hope you liked this video and will consider subscribing to my channel!
    Find me:
    ardalis.com
    / ardalis
    github.com/ardalis
    / stevenandrewsmith
    bsky.app/profile/ardalis.com
    #csharp #dtos #dto #oop #dotnet #visualstudio #webapis #aspnet #aspnetcore
  • НаукаНаука

Комментарии • 109

  • @tomdanielsofficial
    @tomdanielsofficial Месяц назад +70

    Summary:
    1) DTOs should not have logic/behavior 1:03
    2) DTOs should not enforce encapsulation. They don't need private/protected members. 7:26
    3) DTOs should use properties (not fields), otherwise serialization won't work. 8:52
    4) DTOs should only use "DTO" in their name as a last resort. Name them for how they are used. 10:13
    5) These should be modeled as DTOs: 12:05
    - API Request / Reponse objects
    - MVC ViewModel objects
    - Database query result objects
    - Messages (Commands, Events, Queries)
    * Record types can be helpful for DTOs
    * MVC models should be DTOs / MVVM models don't
    * Fluent Validation NuGet Package

    • @mrwalkan
      @mrwalkan Месяц назад +1

      Thanks

    • @meetingattender8132
      @meetingattender8132 Месяц назад +2

      This comment is better than the video thank you

    • @Ardalis
      @Ardalis  Месяц назад

      Thanks!

    • @pierwszywolnynick
      @pierwszywolnynick 26 дней назад +2

      you just saved me 17 minutes

    • @Ardalis
      @Ardalis  26 дней назад +2

      @@pierwszywolnynick What? Check this out:
      1. Read this: ardalis.com/5-rules-dtos/
      2. It should save you at most 12 minutes because you can watch at 1.5x speed; 9 minutes if you watch at 2x
      😁

  • @nrjmatta
    @nrjmatta Месяц назад +1

    Always a pleasure listening and watching your videos.

  • @Robd515
    @Robd515 Месяц назад

    Awesome quality video and very informative. Looking forward to exploring your videos for your expertise.

  • @vadimemelin2941
    @vadimemelin2941 Месяц назад

    Just what I was looking for! Cheers!

  • @clairelist1060
    @clairelist1060 Месяц назад +1

    Your explanation of why we might have a separate DTO for creating a resource vs accessing the resources some other way finally made sense to me!! Thanks!

    • @johnmaloney7174
      @johnmaloney7174 Месяц назад

      I wonder why he used createdate as an example though instead of Id. Clearly you need to include Id (that wouldn't exist in the requestDto) in a responseDto.

    • @Ardalis
      @Ardalis  Месяц назад

      @@johnmaloney7174 Yes that's often true, too, especially for database-generated keys! There was no particular reason why I went with CreateDate aside from the fact that you basically never want some client to send that to your backend (rather than you controlling it) while in some cases you may be OK with client-generated keys (like with GUID keys).

  • @Selbstzensur
    @Selbstzensur Месяц назад

    Thank you for this Video. I really love c# as a programming language. For me it is the most complete one.

    • @Ardalis
      @Ardalis  Месяц назад +1

      You’re welcome and I love it as well.

  • @fernandocalmet
    @fernandocalmet Месяц назад +2

    Great video, Steve. Thank you for sharing

  • @touabdelhak
    @touabdelhak 27 дней назад +1

    Thanks for the content!

    • @Ardalis
      @Ardalis  27 дней назад

      My pleasure!

  • @grzegorzborowski4284
    @grzegorzborowski4284 12 дней назад

    Great stuff. Would be nice to see more of your publicity.

  • @VishalTrivediB
    @VishalTrivediB Месяц назад

    Great tips, thank you very much!

    • @Ardalis
      @Ardalis  Месяц назад +1

      Glad it was helpful!

  • @OzgulEzgin
    @OzgulEzgin Месяц назад

    Thanks for the video Steve. May be you do a video on best practices for mapping dto's as well. Looking forward to it. Best regards.

  • @TammamKoujan
    @TammamKoujan Месяц назад +2

    Nice and clear video; I hoped that it talked about DTO mapping since it is an essential topic

    • @Ardalis
      @Ardalis  Месяц назад +3

      Thanks, I’ll try to cover that (and the fact that you can certainly have static helpers on your DTO types without breaking any of the rules) in a future video

    • @TammamKoujan
      @TammamKoujan Месяц назад +1

      @@Ardalis , what I meant is that mapping is an essential topic for DTOs, and it would be a good addition to this video since people are using different approaches. Some use mapping libraries like AutoMapper, even though this is not widely recommended nowadays, while others do it manually.
      Personally, I use a combination of extension methods and Func Delegate with Expression.

    • @MrSupasonik
      @MrSupasonik Месяц назад

      @@TammamKoujan I for one support the approach with extension methods, but could you elaborate please how do you use Func Delegates with Expressions?

  • @caseyspaulding
    @caseyspaulding 25 дней назад +1

    Great stuff. Thanks

    • @Ardalis
      @Ardalis  19 дней назад +1

      Glad you enjoyed it

  • @mumk
    @mumk Месяц назад

    thanks for sharing!

    • @Ardalis
      @Ardalis  Месяц назад

      You're welcome!

  • @DebugModeVideos
    @DebugModeVideos Месяц назад

    Thanks Steve

    • @Ardalis
      @Ardalis  Месяц назад

      You're welcome DJ!

  • @codefoxtrot
    @codefoxtrot Месяц назад

    Very rich content for a video that could have easily been a mid-level course! Thanks Ardalis!

    • @Ardalis
      @Ardalis  Месяц назад

      Glad you liked it!

  • @AndreNunes-ps5mc
    @AndreNunes-ps5mc Месяц назад

    great content!

  • @theyuribanker
    @theyuribanker Месяц назад +1

    Thanks for sharing this rich content. I have a question about Repositroy. Do you intend to implement Unit Of Work pattern in Ardalis.Specification? or is it not good?

    • @Ardalis
      @Ardalis  Месяц назад +2

      On Specifications, no. On the Repository we ship in Ardalis.Specification package? I don't intend to do so but others can (and have). Honestly that Repository implementation is a bit of a monster because I've accepted just about every pull request from folks wanting "just one more" method on it, so it's no longer as tightly designed as I would prefer. Some day if I have time I may create an Ardalis.Repository that looks to fix this, but for now I have been living with the monster (and only using the bits I need) or just implementing a custom version in my customer's apps (which basically just means copying the base repository class and removing all the things they don't need).

  • @privatesocialhandle
    @privatesocialhandle 21 день назад +1

    No idea why some people are lemon. Thanks for taking the time to provide the knowledge.

    • @Ardalis
      @Ardalis  19 дней назад +1

      Thanks for watching!

  • @joshuawillis7874
    @joshuawillis7874 26 дней назад

    Good video! I'm kinda curious - do you think properties are considered more first-class for C# because of their syntactical sugar options (auto-props, get-only, init-only, etc.), or more for the original reason that they lowered into the common getter/setter pattern and regression, or is there another reason? It feels like the main reason to me is regression for getter/setter.

    • @Ardalis
      @Ardalis  26 дней назад

      All of the above? The language team keeps improving them. Tools and libraries typically work with them out of the box, by default, without additional configuration or hacks. Having proper property support was always one of the things that distinguished C# from Java (some more info here: stackoverflow.com/a/3430218/13729).

  • @alfonsdeda8912
    @alfonsdeda8912 Месяц назад

    Nice video!
    So if I have an entity that have some behavior with create method and validation in it is better to create a separate dto and a separate validator for this entity or is okay to use directly the entity if the behavior regards only the validation inside it self?

    • @Ardalis
      @Ardalis  Месяц назад

      If you’re creating the entity via some user input via an API or form Post, use a DTO for the over-the-wire data. Validate it and let the user know if they need to fix anything. Then call the Create method and pass it the parameters it needs from the DTO’s properties.

    • @alfonsdeda8912
      @alfonsdeda8912 Месяц назад

      @@Ardalis Is good to create an dto and populate from user form and pass directly to create method after validation instead of creating two separate classes?

  • @evildoer1606
    @evildoer1606 Месяц назад +1

    What do you think about using record structs as DTOs? Seen it in some codebases. What are the pros and cons?

    • @Ardalis
      @Ardalis  Месяц назад +1

      I think record struct is basically an improved version of struct, and you should use it in 99% of the places where you might otherwise use a struct.
      Now, as to whether you should use a struct for your DTO types, I think this Stack Overflow question summarizes most of the use cases, and (TL;DR) recommends sticking with classes for most DTO use cases.
      stackoverflow.com/questions/11014501/dto-classes-vs-struct

  • @dallyoluwafemi2827
    @dallyoluwafemi2827 Месяц назад +4

    did you build the ardalis nugets?

    • @Ardalis
      @Ardalis  Месяц назад +2

      do you mean did I author them? yes, that's me.

  • @AlwaysHCYT2
    @AlwaysHCYT2 Месяц назад +1

    Attributes in record fields need "property:". In your example:
    [property:EmailAddress] string Email

    • @Ardalis
      @Ardalis  Месяц назад

      Yep, someone else mentioned that as well. Thanks!

  • @johnmaloney7174
    @johnmaloney7174 Месяц назад

    I would also suggest that your Data Access Layer only returns DTOs - that is, when using EF or EF with a Repo layer, that the DAL/Repo accepts and returns DTOs to/from the App layer. This way the app is clearly decoupled from entities/persistence & any business logic works exclusively with business models (dtos) . Both App & DAL would hold a reference to the Model project, but the App would not hold a reference to the DAL. Repo interfaces would be defined in the Model project but implemented in the DAL project.

    • @Ardalis
      @Ardalis  Месяц назад

      Repository is a DDD pattern. It's meant to work with the Domain Model, which includes your Entities and Aggregates. Those are the types it should accept/return, not DTOs. DTOs are typically an Application concern, and are used for ViewModels and API messages, etc. The only DTOs I typically have in my domain model are domain events.
      For simple apps you can just have your Web/UI layer use repositories, work with the domain model, and do whatever mapping is needed to DTOs. But for more complex apps (like ones that typically require DDD) I am typically using a UseCases project as my Application layer which does all the work of talking to the domain model and mapping DTOs. Then the web layer simply sends messages to the UseCases layer and gets back results with DTOs that are ready for it to use. See my Clean Architecture template on GitHub as an example.

    • @frontendtony
      @frontendtony 8 дней назад

      ​@Ardalis are we building the same app? Lol
      I'm relatively new to Dotnet/OOP/Design Patterns/Clean Architecture/etc, and I've settled on this structure you just explained because it made the most sense to me. Matter of fact, I use a separate "Common" project to store DTOs which I then create mappers for in the application layer to transform entities/queries/commands to their respective DTOs

  • @bensadik
    @bensadik Месяц назад

    I do the same thing, but I add mapping methods:
    record CreateItemRequest(string Name, string Value)
    {
    public Item ToEntity => new Item(Name, Value);
    }

    • @TammamKoujan
      @TammamKoujan Месяц назад +1

      In this way, your DTO is doing more than just transferring data (Single Responsibility Principle); with more complex mapping scenarios, you will end up with a DTO that does many things out of its scope, is less flexible, and is less maintainable. Also, you are adding a dependency on your entity classes and tightly coupling them.

    • @henriquesouza5109
      @henriquesouza5109 Месяц назад

      @@TammamKoujan Yeah, that's like putting the entity construction logic in the request object rather than in the entity constructor (where it should be in the first place). I prefer naming them "Input/Parameters" rather than Request/Dto etc since Request is usually bound to http domain and Dto doesn't mean anything at all.
      If you have a constructor "Item(string name, string value)" and you wanna expose this interface to the http (remember http is just a layer on top of your application), then what happens is you create a class to wrap exactly "name" and "value" function parameters, so why don't you name it so? CreateItem is the function, and name + value are the parameters, therefore CreateItemParameters, CreateItemParams or CreateItemInput (in Input/Output pov).

    • @Ardalis
      @Ardalis  Месяц назад

      Adding static helpers to map to/from other types is fine IMO. Extension methods probably even better, though. Avoid instance methods since those break first rule and introduce issues others are commenting on.

    • @bensadik
      @bensadik Месяц назад

      @@Ardalis extension methods are a great idea for this particular purpose, but it’s only a C# thing, for other languages this is just fine IMO

  • @Ardalis
    @Ardalis  26 дней назад

    Article version: ardalis.com/5-rules-dtos/

  • @maciejwawoczny1174
    @maciejwawoczny1174 15 дней назад +1

    If my API return "UserResponse" which contain other class inside, how to name that inner class?
    class UserResponse {
    public InnerClassResponse/InnerClassDTO/InnerClass?
    }
    Same example with Requests etc

    • @Ardalis
      @Ardalis  13 дней назад

      Something like this:
      class CreateUserResponse
      {
      public UserDto User {get; set;}
      // other properties, metadata if needed
      }
      In some cases it might make sense to have a standard Response structure in which case the resulting data might always go into a "Payload" or "Result" property, which might be of type object or string.

  • @keesdewit1982
    @keesdewit1982 Месяц назад

    Rocky Balboa teaching me about DTOs. I love it 😅

    • @Ardalis
      @Ardalis  Месяц назад

      Heh, used to be folks thought I looked like Alec Baldwin from 30 Rock. Now with long hair I guess I'm Rocky... I'll take it. :)

    • @keesdewit1982
      @keesdewit1982 Месяц назад +1

      @@Ardalis You are just a nice guy ;) Thanks for providing these videos.

  • @JjKoller85
    @JjKoller85 Месяц назад +4

    What is your take on inheritance on DTOs (especially Request and Response of WebAPIs)? I've seen it quite often in the past years. Following your first rule, I would assume that we rather should duplicate properties on DTOs?

    • @ddrsdiego
      @ddrsdiego Месяц назад

      This is a really good question and given my years of experience in integrations I can say that starting with inheritance seemed to make sense but over time each endpoint starts to gain more life and management starts to become complex due to inheritance. What has worked for me is maintaining a canonical model and sharing it with all areas and yes, repeating properties in Requests and Responses

    • @Ardalis
      @Ardalis  Месяц назад +5

      I used to use inheritance for instance between a Create and an Update DTO I might have Update inherit from Create and just add an Id property (since db-generated Id wouldn’t be on a Create record). But it often turns out that’s not where the differences end and these days I just keep the types separate so there is no coupling between them. The duplication hasn’t caused me any troubles yet.

    • @mmuekk
      @mmuekk Месяц назад +1

      I use interfaces instead inheritance

    • @jackeinstein2184
      @jackeinstein2184 Месяц назад

      @@mmuekk could you please explain how?

  • @vasant2411
    @vasant2411 Месяц назад

    How should we name response object return from command

    • @Ardalis
      @Ardalis  Месяц назад

      CommandNameResponse probably

  • @scotmcpherson
    @scotmcpherson 11 дней назад

    These rules although great for abstraction, have an impact of runtime efficiency. When a server is dealing with lots of lots of concurrent realtime data streams, this can have a negative impact.

    • @Ardalis
      @Ardalis  11 дней назад

      Which?

    • @scotmcpherson
      @scotmcpherson 10 дней назад

      @@Ardalis Have you ever looked at runtime optimized code? It's not organized, and can be hard to read. Prototyping with organization is important, but once you go into release, if it needs every sliver of performance, then your organization gets torn to shreds.

  • @AlFasGD
    @AlFasGD Месяц назад

    I strongly disagree with the point about using properties over fields. Properties are very cumbersome to write, and fields are straight-foward. You can setup your serializer of your choice (Newtonsoft, System.Text, or any other) to also discover the fields in your DTO. The only drawback that fields have is that they do not implement interfaces, and in the case that your DTO implements one, you have to stick to properties.
    Speaking of interfaces, you did not touch the subject of having all those common fields like ID, email, first and last names, etc. Oftentimes you are mapping them out individually, having more boilerplate code for passing all that information around, than actually using and processing it. Sometimes, it might come in handy to use interfaces to abstract away that responsibility of mapping objects like this, and allow for multiple objects to be mapped out via their interface properties.

    • @spacemanjack777
      @spacemanjack777 Месяц назад +1

      Writing properties is cumbersome... really? But a custom serializer configuration instead of ordinary properties and be done with it? Yes, properties takes a few more characters to type than fields, but most of the time nobody is actually typing in those are they? I mean, code intellisense.

    • @AlFasGD
      @AlFasGD Месяц назад

      @@spacemanjack777 whatever you do to make your property declaration process shorter, it's still longer than fields. That's all.

    • @Ardalis
      @Ardalis  Месяц назад

      Properties are trivial to write these days and almost always auto-completed by your IDE or else easily copy/pasted when you're creating several of them. Leveraging the default behavior of the framework instead of requiring customization is way more valuable than trying to save a few characters on declaring your class members, IMO. But if it's working for you, go for it.

  • @anomalii7720
    @anomalii7720 Месяц назад +4

    But, for the record, it's your 5 rules. And that doesn't mean anything. 🙂

  • @wandie87
    @wandie87 Месяц назад

    Great video.
    I typically end up with multiple DTOs (Whether these are Request or Response types) for specific use cases. For example:
    UserResponse.cs
    UserWithAddressResponse.cs
    UserWithBirthdateResponse.cs
    Each response would be used for a different API request to ensure I am only sending the required information back over the wire (no oversharing).
    Is this problematic? If so, how would be best to improve upon this?
    I feel I end up with a lot of replicated code...
    Thanks

    • @Ardalis
      @Ardalis  Месяц назад

      I'm with you. I'd rather have independent DTOs for different API endpoints with a bit of duplication between them but no coupling than have some inheritance hierarchy that might bite me later with an unforeseen consequence of sharing. I've been building APIs for a LONG time and my trend has been toward increasingly independent endpoints. In the beginning, like most .NET devs of the time, I had big controllers with big DTOs and minimal duplication (DRY all the things!) but now I use API Endpoints (usually fast-endpoints.com) with bespoke Request and Response DTOs for each endpoint (REPR Pattern) and I've found this makes it MUCH easier to build and modify individual endpoints without risk of breaking others.

    • @wandie87
      @wandie87 Месяц назад

      @@Ardalis I agree.
      How do you deal with nested DTOs? Take my UserWithAddressResponse.cs example above.
      Do you have a child DTO for address that you reference or do you do it all in the single top level DTO? If the child reference route, is this shared between other DTOs or bespoke to the user object?

    • @Ardalis
      @Ardalis  Месяц назад

      @@wandie87 Probably an AddressDTO with the basics, and an array of them for the UserWithAddress (assuming they have more than one) or just a property if only the one. I've never really thought about my personal "rules" for such things but thinking about it now I tend to create very simple "FooDTO" types for "leaf node" objects that have no references to other objects (especially collections). These will usually live in my UseCases/Application layer since that layer is usually responsible for returning them to the UI layer in response to queries/commands/messages sent to it.
      The leaf node DTOs are (somewhat) reusable, and may be (re)used to compose more custom Request/Response etc DTOs. The more complex DTOs (like UserWithAddress for instance) are usually less reusable and more customized to a particular operation.

    • @wandie87
      @wandie87 Месяц назад

      @@Ardalis I’d never put much thought into it either until I watched your video. Triggered me to have a think about how I structure this stuff going forward and augment some of my own rules into the ones you provided.

  • @doubleMSW
    @doubleMSW Месяц назад

    If you're using EF Core and reference the id from one "DTO" to another (i.e. OrderDTO, OrderItemDTO, ProductDTO) in EF Core I've aways seen a reference in the DTO:
    public class OrderDTO
    {
    public Guid Id { get; init; }
    public string OrderNumber { get; init; }
    ...
    // If you had a many to many there would be reference to a collection from a link entity
    // If you had a one to many there would be a reference to a collection of the many side (i.e. OrderDTO and OrderItemDTO which linked to a ProductDTO)
    }
    public class OrderLineItemDTO
    {
    public Guid Id { get; init; }
    public Guid OrderId { get; init; }
    public int ItemNumber { get; init; }
    ...
    public OrderDTO Order { get; set; }
    public ICollection LinkOrderItemProductCollection { get; set; }
    }
    I don't want to continue down the rabbit hole here, hopefully you get the jest of what I'm referring too...
    Thoughts???

    • @Ardalis
      @Ardalis  Месяц назад

      EF Core shouldn’t be working with DTOs directly - I assume you’re talking about mapping entities to DTOs, right?

    • @doubleMSW
      @doubleMSW Месяц назад

      @@Ardalis correct

    • @johnmaloney7174
      @johnmaloney7174 Месяц назад +1

      It's a good question, but the navigation properties that exist on entity object don't need to exist on the dto. If you use Automapper, it will populate those properties with the related objects/object collections without hassle.

    • @Ardalis
      @Ardalis  Месяц назад +1

      @@johnmaloney7174 Exactly. Sometimes you'll want the related objects in the DTO structure, sometimes you might just want the IDs. For instance when getting a collection of Orders from a GET /orders endpoint you might only get the top level order info, but then if you GET /orders/123 you will often get additional information including the details of the line items. The "shape" of your DTO data will often vary with context, and won't often correspond directly to your domain entity or data model.

  • @mesutdemirci7933
    @mesutdemirci7933 Месяц назад

    Great tips, thank you very much!

    • @Ardalis
      @Ardalis  Месяц назад

      You're welcome!