I'd like to know which of the following is better programming practice:
// Below is the contents of a dummy method which is passed a boolean "condition" as a parameter.
int valueA = 3;
int valueB = 5
if (condition == true) {
return valueA
}
else {
return valueB
}
Alternatively, I could write the same code this way:
int valueA = 3;
int valueB = 5
if (condition == true) {
return valueA
}
return valueB
In both cases, valueB will only be returned if condition equals false, so having an "else" isn't required, however is it better practice to include it anyway?
I'd like to put the else there as well, for readability's sake. However, you could also write a shorthand if/else statement:
return condition ? valueA : valueB;
Again, it's your own preference how you write it.
Take the following Example, to see how the use of else helps you to understand the Code better
if (inputVar == thingOne) {
doFirstThing();
} else if (inputVar == secondThing) {
doSecondThing();
} else {
doThirdThing();
}
I could write it like this aswell.
if (inputVar == thingOne) {
doFirstThing();
return;
}
if (inputVar == thingTwo) {
doSecondThing();
return;
}
doThingThree();
return;
Now ask yourself which code looks clearer and where you understand the most.
It really comes down to which way most clearly shows what the code is doing (not necessarily which bit of code is shortest or has the least indentation).
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