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?
I’d like to know if using NULL as a key in a Map object
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is generally not considered good style.
Since
NULLtypically 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.
Rather than storing the default color in the
HashMapusing aNULLkey, 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
NULLvalue 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 aNULLstring that you want the color for.