Search code examples
springspring-bootdto

Is it a good practice to add repository to a DTO class?


I have a DTO object, it needs EntityA from DB for conversion to EntityB. Where should the convertion be done?

Is it a good practice to have a static method right in DTO class and a repository instance to load an object?

I do appreciate your answer!


Solution

  • The law of Demeter is about reducing coupling by minimizing the things an object talks to. Here the method needs an A to make a B, so let it take A as a parameter. The Repository that retrieves As is one step removed, and should be left out.

    The usual analogy is that when I go to pay a cashier for something I take the money or credit card out of my wallet and give it to them, I don’t hand them my wallet and let them dig around in it.