Home > Software design >  Should DTO contain an enum or not
Should DTO contain an enum or not

Time:12-13

Let's say I have an Entity that has an enum property.

enum Property {
    A, B, C;
}

And I would like to have similar DTO for this Entity, should the DTO have Property as an enum or a String?

What is the most preferred way to pass an enum in a DTO class to be converted into an enum and vice versa.

CodePudding user response:

There's a lot of different opinions on that. Some people are very strict in the separation of DTO and Entity classes. Other people say you should focus on Domain classes, and use infrastructure adapters instead of DTO's and Entities.

In my opinion, simple immutable Value classes can be shared between DTO's and Entities. E.g. an Instant or LocalDate, an enum, or some domain-specific Value Object. You only need to make sure they can be converted correctly from or to the format needed for data transfer, and they are immutable, i.e. only a constructor and getters, no setters.

So I would use the enum in both the DTO as in the Entity.

CodePudding user response:

should the DTO have Property as an enum

Of course it should. Proper typing is the first line of data validation. If the value of the property is rectricted to a certain predefined set, why should it not be reflected in the DTO?

Note that this does not necessarily mean the enum should be shared between the DTO and anything the DTO is ultimately mapped onto. That's a different question altogether, and different people might have different ideas about that.

  • Related