How could I improve nested if-else statements, eg in the following code example (the numbers are not neccesary the same, just example):
boolean a, b;
int result = 0;
if (a && b) {
result = 3;
} else if (a) {
result = 1;
} else if (b) {
result = 2;
}
Could this be written better somehow? Or would you think it's ok just as it is?
For the particular numbers given:
int result = (a ? 1 : 0) + (b ? 2 : 0);
In the more general case, there's really not much wrong with the code you've already written. It's pretty concise, perfectly legible and easy to comprehend.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With