Get rid of many DTO files

Author:

In many projects I’ve worked, there’s usually a folder with a lot of DTO class files.

I believe that keeping many files at the solution tree for DTOs could be very annoying, specially as it takes more time for the compiler and the IDE to know the existence of this files.

The idea is to replace classes used like for body parameters

Below there’s an example of solution tree we do not want to have.

Example of DTO folder

The record keyword

This keyword came to save some time for the developer and a few lines for the project.

When a DTO is used to receive parameters from the FrontEnd these DTO must be immutable.

Let see a practical example of how the record helps.

Converting this class to a record class it would be only a single line of code.

When you declare a primary constructor on a record, the compiler generates public properties for the primary constructor parameters.

So instead of having a folder with so many class files, I proposed to have one single file with DTOs declared as records.

One DTO file representing all DTOs in records objects

At the end your structure would be like this

Conclusion

With this approach you would save lines of code as well as compilation time, also need to take account that when opening the project solution, the IDE will be faster when load the entire project as we have less files.

Hope you liked it!

Leave a Reply

Your email address will not be published. Required fields are marked *