Can you convert this code to not use an IF statement?
This is out of pure curiosity. A senior developer at work expressed his opinion to be regarding IF statements and said that we should write code that doesn't use IF statements.
His reason being that you write better code and have a direct app flows over conditional flows.
It was his opinion and nothing to be taken literal however I want to know, is the following code possible without an IF statement?
Code:
int input = getUserInput();
if(input > 10) {
handleHigh();
} else {
handleLow();
}
Be as creative as you want. I tried, I couldn't think of anyway on how to do it.
Edit;
Update! Just found one excellent way to do this!
Code:
NavigableMap<Integer, InputHandler> messages = new TreeMap<>();
messages.put(Integer.MIN_VALUE, new DefaultInputHandler()); //everything
messages.put(1, new LowInputHandler()); //values from 1..9
messages.put(10, new HighInputHandler()); //values after 10
messages.put(15, new DefaultInputHandler()); //everything
System.out.println(messages.floorEntry(7).getValue().getMessage()); //LowInputHandler.getMessage()
System.out.println(messages.floorEntry(11).getValue().getMessage()); //DefaultInputHandler.getMessage()
System.out.println(messages.floorEntry(15).getValue().getMessage()); //DefaultInputHandler.getMessage()
In this case it would be:
Code:
messages.floorEntry(input).getValue()
Update again: Try without any sort of conditional such as x > y!