3 ms·
Nulls can be particularly pernicious in Java because of auto-unboxing. E.g., imagine you got a NPE from this: String summary = getUserSummary( user.getId(
by jtheory 11y ago
Nulls can be particularly pernicious in Java because of auto-unboxing.
E.g., imagine you got a NPE from this:
String summary = getUserSummary( user.getId() );
...you'd think "user" must be null, right? But it's quite possible that user.id is a Long, the current value is null, and getUserSummary() requires a long primitive argument.
This compiles just fine, and at runtime the Long object will be auto-unboxed to a primitive long... unless it's null.
Surprise!
But things like Optional do help; doing a code review for the things that may be null will fix these kinds of mismatches (and you'll avoid relying on auto-unboxing). The above code is broken -- either user.getId() can never be null (in which case it should be a primitive already) or it might sometime be null, in which case this code must not allow auto-unboxing.
- jdmichal 11y agoI had a fun one with this once. It looked something like this, using your `user.getId` method: int userId = p ? 0 : user.getId(); We spent a few hours staring at this trying to figure out why there was a `NullPointerException` on a line dealing with `int` values. Eventually realized that `thing` was really an `Integer`, causing the entire trinary to be an `Integer`, which was then being unboxed to an `int`.