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*

19
  • 7
    Catching NullPointerException and returning null is horrible to debug. You end up with NPE later on anyway, and it's really hard to figure out what was originally null. Commented Sep 14, 2013 at 8:44
  • 26
    I'd downvote if I had the reputation. Not only is null not necessary, it's a hole in the type system. Assigning a Tree to a List is a type error because trees are not values of type List; by that same logic, assigning null should be a type error because null is not a value of type Object, or any useful type for that matter. Even the man that invented null considers it his "billion-dollar mistake". The notion of "a value that might be a value of type T OR nothing" is its own type, and should be represented as such (e.g. Maybe<T> or Optional<T>). Commented Nov 20, 2013 at 15:57
  • 4
    As of "Maybe<T> or Optional<T>" you still need to write code like if (maybeNull.hasValue()) {...} so what is the difference with if (maybeNull != null)) {...}? Commented Apr 1, 2014 at 11:06
  • 3
    As of "catching NullPointerException and returning null is horrible to debug. You end up with NPE later on anyway, and it's really hard to figure out what was originally null". I'm totally agree! In those cases you should write a dozen of 'if' statements or throw NPE if business logic imply data in-place, or use null-safe operator from new Java. But there are cases when I don't care about what exact step give me null. For example calculating some values for the user just before showing on the screen when you do expect data could be missing. Commented Apr 1, 2014 at 11:32
  • 4
    @MykhayloAdamovych: The benefit of Maybe<T> or Optional<T> isn't in the case where your T might be null, but in the case where it should never be null. If you have a type that explicitly means "this value might be null -- use with caution", and you use and return such a type consistently, then whenever you see a plain old T in your code, you can assume it is never null. (Course, this would be a lot more useful if enforceable by the compiler.) Commented Nov 7, 2014 at 19:55