Should the DTO of a datamodel have primitive Data types only for serialization in Java?

I have created a data model Student as follows:

class Student {
private final Name name;
private final Grade finalGrade;
private final Roll rollnumber;
}

Name is an object of two Strings – firstName and lastName, Grade is an enum and Roll number is an object of two integers – class number and seat number. To store this data in DB, I am serializing this data as a JSON.

So I have created a DTO. So my question is, can the DTO also have the same objects Name, Grade and Roll or should it be in primitive datatypes?

Answer

The purpose of DTO is used to pack some data to transfer to other clients/systems across the network. One of the popular use case is the WEB API . So taking JSON WEB API as an example ,the structure of the DTO is mainly depends on your API response body structure and the capability of the underlying framework that you use to seraialzie the DTO to a JSON.

If the underlying framework supports serailzing some non primitive types (which most modern one will) , I don’t see any reasons that you do not use this feature and restrict yourself to only use primitive data type in the DTO .

For example, it is very common to include a LocalDateTime in the DTO and then the framework will serialize to a valid ISO 8601 data string such as 2020-04-23T11:11:12.511Z. Not to mention including a List / Set in the DTO.

If you restrict yourself to only use primitive type in the DTO , it somehow means that all things in the JSON response will be flatten out and there is no more nested structure.It may be okay in a very simple case but not so good when your data model is a little bit richer which can be expressed much better with some nested structure.

Leave a Reply

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