Issue
AFAIK I should avoid if/else statements as much as I can.
I've chosen this approach and I'm looking to see if it is valid.
FXMLLoader fxmlLoader = new FXMLLoader(HelloController.class.getResource("UserPanel.fxml"));
if(receivedJSON.get("isAdmin").toString().equals("1")) {
fxmlLoader = new FXMLLoader(HelloController.class.getResource("AdminPanel.fxml"));
}
//....
//....
//code that needs to be run so I can't return in the if statement
//....
I don't really like it because if the isAdmin
attribute is 1, I have to do two assignments.
What would be the best and professional way to avoid an if/else in this situation?
Thanks!
Solution
This guidance to not use if
if possible only applies if you optimize code that you execute millions of times per second. You probably only create a very small amount of FXMLLoaders each time you run the program.
Even if you estimate a high amount of 40 CPU cycles lost, at 4 Ghz that is still only 10 nanoseconds on a failed branch, so nothing you should worry about.
In fact, even if you only take 1 minute to write this post, and you create 100 FXMLLoaders (1 microsecond in total), and the branch predictor fails 100 times in a row (will not happen), it still took 60 million times longer to write the post than the time you could theoretically save.
Or if you create a server program and you only need 1 minute to optimize it and it creates one FXMLLoader in an if statement per second and the branch prediction fails every time, then that server needs to run for 190 years continuously for it to be worth it even if you value server single core CPU time the same way as developer time.
Answered By - Konrad Höffner
Answer Checked By - Robin (JavaFixing Admin)