Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NULL as a key value in a Map

I'd like to know if using NULL as a key in a Map object is considered good style and if not what are the alternatives?

like image 558
Aleksandar Savkov Avatar asked Nov 25 '11 15:11

Aleksandar Savkov


2 Answers

This is generally not considered good style.

Since NULL typically indicates an undetermined or unset value, it is generally confusing to use as a key to a map. (although, there may be specific circumstances where it makes sense)

The alternatives depend on the situation, so let me use an example. Let's say that we want color specific strings in a text, and we also want a default color for text which doesn't match any of the strings.

private HashMap<String,Color> stringColors;
private Color defaultColor;

Rather than storing the default color in the HashMap using a NULL key, put the default color in the specific variable. This makes it really clear to anyone viewing the code exactly what this color means.

The driving factor, I would say, is if you will actually have a NULL value somewhere that can be directly looked up in the map. (this doesn't happen often, in my experience) In this specific example I gave, the default color would be used for any strings which aren't in the map. In this case, there isn't a NULL string that you want the color for.

like image 112
Erick Robertson Avatar answered Sep 24 '22 23:09

Erick Robertson


I would personally recommend using a Null Object (see Null Object Pattern), or some sort of default key, rather than null as a key. Using null always means you have to code to defend against NullPointerException, and should be avoided whenever possible.

Edit

As an example, if you are creating an API that will allow users to add values to a map (be it a home made Map implementation, or a utility class that uses a map to store its data) and your first version let them use null as a key, you will always have to support null keys. So either your backing Map will have to be an implementation that accepts null keys, or you will have to trap suck keys, and replace them with a different key that will represent a null key.

As @Erick Robertson mentionned, there are cases where accepting null keys makes sense. However, if you are designing an API, you should really make sure that you want to handle such keys, as it always means more code to check for null. And it also means more defensive code for the clients of your API.

like image 31
Laf Avatar answered Sep 22 '22 23:09

Laf