Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement List, Set, and Map in null free design?

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.

like image 957
Pyrolistical Avatar asked Apr 09 '26 09:04

Pyrolistical


1 Answers

Two possible solutions:

  1. 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.

  2. Functional languages use Maybe in similar situations. This article explains how to implement Maybe in Java.

like image 134
Igor Krivokon Avatar answered Apr 10 '26 21:04

Igor Krivokon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!