开发者

Can I use DTO composed of other classes or just primitives?

开发者 https://www.devze.com 2023-03-10 17:20 出处:网络
If I have two classes: public class Person { public String name; public int age; } public class Address { public String address;

If I have two classes:

public class Person {
   public String name;
   public int age;
}

public class Address {
   public String address;
   public int number;
}

Should I construct a DTO like the following:

public class MyDTO {
    public Person person;
    public Addr开发者_如何学Pythoness address;
}

or this:

public class MyDTO {
    public String name;
    public String address;
}


You can have whatever you want in a DTO, but the basic idea is to transport the smallest amount of data possible.

Remember though, that the purpose of a DTO is to transfer data around, quite possibly between JVM boundaries, for example when using EJBs. If this is the case, you must remember to make sure that all the classes that are referenced in your DTOs are serializable.

In the example you have above, the simplest DTO would be

public class MyDTO {
    public String name;
    public String address;
}

and could be easily consumed.

If your consumer is going to use a Person and Address class however, its probably easier to place them in the DTO so that they can be consumed easier.

There is no "one size fits all" answer. It depends on your environment and how you need to work.

0

精彩评论

暂无评论...
验证码 换一张
取 消