While I was recently working at a big company, I noticed that the programmers there followed this coding style:
Suppose I have a function that returns 12 if the input is A, 21 if the input is B, and 45 if the input is C.
So I can write the function signature as:
int foo(String s){
if(s.equals("A")) return 12;
else if(s.equals("B")) return 21;
else if(s.equals("C")) return 45;
else throw new RuntimeException("Invalid input to function foo");
}
But on code review I was asked to change the function to the following:
int foo(String s){
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 12);
map.put("B", 21);
map.put("C", 45);
return map.get(s);
}
I can't convince myself on why the second code is better than the first. The second code would definitely take more time to run.
The only reason to use the second code can be that it offers better readability. But if the function is getting called many times then wouldn't the second function slow down the running time of the utility calling it?
What do you think about this?
Best Answer
The point is to move the creation of the hashmap outside the function and do it once (or just less times than otherwise).
However java has since java7 been able to have (final) strings in switches: