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?
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.
There is no record with id
of null
therefore the method should do whatever it does if given a "valid" id
for which there is no record. That is the principle of least surprise. The consumer will have coded for the case of not found so they should be covered.
There is one thing, what is the id
of a new record that hasn't been persisted yet? That may cause you to deviate your behaviour if it happens to be null
总是最好使用NullPointerException
因为在Entity集合中没有找到ID中的值。
上一篇: 在公共方法中检查参数的先决条件