How to handle null from the outside?

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:

  1. 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.
  2. 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).
  3. 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
  4. 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?

1 Like

You could use 3rd party validation for this, e.g. Hibernate validator. As for workflow it could be like following. Make DTOs fields nullable. Mark fields that should not be null with @NotNull annotation. After Jackson bind the fields use Hibernate validator to check DTO fields, it will check the fields and return errors if any. If validation is successful you can safely use !! operator when copying DTO fields to domain class.

Jason parser need to be aware of nullable annotations, try moshi-kotlin :+1:

moshi-kotlin does indeed look interesting. Thanks!

Hello, what do you think about using a library like Konad GitHub - lucapiccinelli/konad: Simple Kotlin monads for every day error handling for this purpose? It provides a simple API for nullables composition and error handling. Check out also this article for advanced use cases Kotlin Nullables: How to Compose Them Right | Hacker Noon