Search code examples
javanullpointerexceptionillegalargumentexceptionmethod-parameters

Service layer: What to return if query argument is null?


Lets say we have a service method getById(Long id) which returns an entity based on its id. What would be the proper action to do in case id is null?

Throw IllegalArgumentException?

Throw NullPointerException? (guavas Preconditions.checkNotNull does this)

return null?

Since there can never be an entity with id == null, returning null does not seem that bad? I mean if the id does not exist the method will return null anyway.

Preconditions are nice one-liners but throwing a NullPointerException seems extreme in this case.

Whats the "best practice" here?


Solution

  • Passing null to such a method indicates a bug. Nobody would ever want to find the entity which has a null ID, since no such thing can exist. So this probably mean that there has been a binding problem in the UI layer, or that the caller forgot to add a hidden ID field in its form, or whatever.

    Returning null hides the bug, or makes it more obscure. Throwing an exception spots the bug early, with a clear error message, which allows fixing it early, and makes the application ultimetely more robust.

    The convention for non-nullable arguments which are null is to throw a NullPointerException. That's what I'd do.