I have an application where the server receives Json objects that get mapped to DTOs by the Framework (Jersey with Jackson). Since incoming data is not always like it should be, all fields in the DTOs are nullable. However, if I use these DTOs to create or update domain objects (in the sense of Domain Driven Design), most of the time null
is not allowed.
In Java I would use nullable parameters/fields (since there is no other option) plus some kind of validation like Bean Validation or Guava preconditions. In Kotlin nullness can be checked by the compiler, so it would feel somewhat wrong to make parameters/fields nullable just to be able to report that they are null!
The following tiny example illustrates that:
class ItemDto(val name: String?)
// where to ensure name is not null?
class Item(val name: String)
I see several possibilities:
-
Making the field in the domain class (
Item
) nullable and require not null in the implementation.- Pro: all validation at one place
- Contra: Would make the interface of the class less understandable and would add otherwise useless code.
-
Checking for
null
at the DTO level.- Pro: Since
null
can only appear in the DTO, null checks would be more appropriate here. - Contra: It might be tempting to add some more validation and that would be the wrong place then.
- Contra: Not sure whether exceptions during the mapping are leading to the desired error messages (have not tried it yet).
- Pro: Since
-
Checking for
null
in the service- Pro: DTO remains simple and dumb
- Pro: Checks can vary between usages (maybe sometimes
null
is ok) - Contra: may lead to redundant checks if the DTO is used in more than one place
-
Making DTO fiels non-nullable
- Pro: simple, no code
- Contra: hard to return useful error messages
How would you perform null checks in this scenario?