Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return "null" on primitive return type function?

Tags:

java

I have a function which returns an int value for a given key (from a HashMap<String, Integer>). If the key doesn't exist, I want to return something the caller can check for. It seems that, most commonly, this would be a "returns -1 if key doesn't exist" kind of thing. However, I can't reserve -1 for that purpose in my case, because negative numbers are feasible values for keys which do exist.

The only other options I have been able to come up with are the following:

  1. Change return type to Integer wrapper class and check for null
  2. Return something very unlikely, such as Integer.MIN_VALUE
  3. Make an additional boolean keyExists(String key) function which should always be called first
  4. Switch to float and use NaN instead

I am writing this in Java, but people from similar language backgrounds are welcome to post. Thanks!

like image 610
idolize Avatar asked Jul 22 '10 19:07

idolize


1 Answers

The first option is, in my opinion, the cleanest. Magic numbers like -1 and Integer.MIN_VALUE are kind of messy, especially when the values aren't intuitive. That is an idiomatic C solution, which Java developers will hate you for. Depending on what you're actually using this for you could also throw a "KeyNotFoundException" if this only happens in "exceptional" circumstances.

like image 109
Hut8 Avatar answered Oct 11 '22 21:10

Hut8