Is it okay to transport a DTO inside of a DTO

design-patternsdtoservices

Let's suppose we have to entities, X and Y where Y is part of X, being this:

class X {
     private int fooX;
     private List<Y> fooY;
}

class Y {
      private long barX;
      private int barY;
      private short barX;
}

Wanting to transport data from a service to a different module, where the data relies from X entities, I'm creating a DTO for it

However, X has a list of Y entities inside of it, so simple data couldn't be used to represent them

So, is it okay that I create a DTO for Y and transport it inside of X DTO?

Thanks in advance

Best Answer

DTOs are used to transfer data between parties. As the definition suggests your objects are valid as long as they are designed for data transfer. That means they must carry no logic (or methods in other words), no private field (except back fields), and only use a set of limited data types (or other DTOs) because of serialization issues.

Another responsibility of Data Transfer Objects is to reduce the number of calls, because that helps both the simplicity and remote call numbers if your services are distributed. So you should try to get as much data as you can in a single call.

Finally, refactoring your objects in order to make your code more readable to achieve these purposes is absolutely a good practice. Feel free to extract classes from DTOs.