Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good Programming Practice regarding conditional return statements [closed]

Tags:

java

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?

like image 647
Cal Banders Avatar asked May 01 '26 13:05

Cal Banders


2 Answers

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.

like image 74
stealthjong Avatar answered May 03 '26 02:05

stealthjong


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).

like image 32
CodeFanatic Avatar answered May 03 '26 03:05

CodeFanatic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!