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?
switch
seems more appropriate thanif-else
). But at some point, it becomes problematic. The main advantage of using a Map is that you can load it from a file or a table etc. If you are hard-coding the input to the map, I'm not seeing a lot of value over a switch.