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