Its great when you can return a null/empty object in most cases to avoid nulls, but what about Collection like objects?
In Java, Map returns null if key in get(key) is not found in the map.
The best way I can think of to avoid nulls in this situation is to return an Entry<T> object, which is either the EmptyEntry<T>, or contains the value T.
Sure we avoid the null, but now you can have a class cast exception if you don't check if its an EmptyEntry<T>.
Is there a better way to avoid nulls in Map's get(K)?
And for argument sake, let's say this language don't even have null, so don't say just use nulls.
Two possible solutions:
Provide a contains(key) function. Throw an exception if get(key) is called for a non-existent key. The downside is: calling get() after contains() duplicates operations; not efficient.
Functional languages use Maybe in similar situations. This article explains how to implement Maybe in Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With