Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

4
  • 10
    Nice answer, especially mentioning asserts. I came from C and use them constantly. As to Null Objects, they are NOT a silver bullet. I have often spent hours debugging code which turned out to be a Null Object being used, doing nothing (or returning its defaults) when a NPE would have been indicated the problem much more clearly. So then you'll have to do a "Null Object check" instead of a null check, and haven't won anything, actually lost clarity. Nowadays, if I can't avoid null, I just document it clearly and that's it. Commented Dec 25, 2021 at 0:01
  • 2
    Writing this.bar = Objects.requireNonNull(bar); is a good use of this method, because you're not about to use this.bar. This way, you get the exception when an invalid null object is being passed, rather than when you try to use it. But, it often gets used this way: Objects.requireNonNull(getThing()).doThingStuff(); Here, the call to Objects.requireNonNull() doesn't change the behavior at all, it throws the NPE either way. It is best used when you are saving an object for later use. In my second example, the exception is useful. It helps track down the bug. Commented Jul 9, 2022 at 3:45
  • 3
    Should we suggest using exceptions for control flow though? While it's technically a solution that works, programmers should remember that exceptions should only be used to catch unexpected situations. When validating a user's input, invalid input should ideally not lead to exceptions being thrown. Commented Jul 12, 2022 at 12:34
  • Something to add to this answer is that if null is a valid return value they can use the Optional to wrap the value and add handling logic there (assuming Java 1.8+) Commented Jul 5 at 15:13