r/java • • Jun 27 '16

Null pointer exceptions hell

http://dobegin.com/npe-hell/
0 Upvotes

18 comments sorted by

View all comments

3

u/[deleted] Jun 29 '16 edited Jun 29 '16

Option types are known as Nullable<T>, Optional<T>, Option<T> or Maybe T in different programming languages (where “T” denotes a data type). Such type lets you express an explicit intent that a value can potentially be null and requires an explicit cast if you want to get to a contained non-null value.

Saying that Optional is something that may contain null is like saying that ArrayList of size 0 may contain null which is not true. Optional is more like collection of max 1 element. Some collections may contain null but their size must be bigger than zero first (because null is a valid element of this collection). Try this code:

ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(null);
System.out.println(arrayList.size()); // prints 1, not 0

Also languages like Haskell or Rust doesn't hide null in Options. They just doesn't provide null ref/pointer. If you try to get value when it's absent you may even get problem with compiling your program. And that's nothing to do with null. Optional in Java may be used to solve similar problems but that doesn't mean they are similar concepts.