Should i use nullable or default values in data classes?


I have an endpoint that receives a data class object, some properties can be not sent, but it is required and I will validate before enter in my system. After my data is valid, i will convert to entity and do some stuffs, so my classes will be like this:

data class CreateCategoryRequest(

  val name: String?,

  val price: BigDecimal?

class CategoryEntity(
  var name: String,
  var price: BigDecimal,    

When I try to convert request to entity I should deal with nullable property doing some cheks (checksNonNull or !!), so my question is: should I use default value or check values again in convert time?

It depends on what you choose null to mean and what you think is best for your use case. In this case, it sounds like you could use null to mean the value was not sent as part of the request.

Is it expected to send a request without a name or price? Is there a natural default ( = “Unnamed” and price = 0)? Is it always an error for a request to be received missing one of those values? Are you receiving these requests from a source that cannot guarantee the non-nullness of those values (e.g. receiving them from REST or DB that does not enforce non-nulls)?

Null can mean a few things. If you want to represent a request with an absence of a value for name or price, I think null is a good solution. If you had more complex classes other than String and BigDecimal you would want to compare using null with the other classes possible “empty value” alternatives (i.g. if your request included shipping options using ShippingOptions.NONE may be more appropriate than null).

Sometimes it helps to have your class, your request class, allow non-final (var) properties that default to null so it can be used as a simple builder. That way you can collect the values more flexibly before the final “build” and validation. Since your request is only two fields you may not benefit from this kind of simple builder.

I wouldn’t use !! if I were you. The !! operator is designed to be ugly and shouldn’t be used unless you really, really, really know better than the compiler. It should not be used as a validation check for null. If you think it would ever throw a null pointer, don’t use !!.

1 Like