3

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?

lxcky
  • 1,668
  • 2
  • 13
  • 26
Cal Banders
  • 33
  • 1
  • 3
  • 3
    I *think* the better way is to have another variable for the return, say `result`, then set it in your `if-else`, then at the end, `return result`. In this way, you'll just have a single return statement. – lxcky Sep 18 '14 at 08:22
  • @J.Lucky I disagree. If you miss some condition, you will return your default value, even if you didnt want to – stealthjong Sep 18 '14 at 08:23
  • 2
    It is definitely better practice to write `if (condition)` than `if (condition == true)` at least. – Keppil Sep 18 '14 at 08:23
  • if things get more complex you should or in some cases u need to use if/else, given your examples it does not matter really. For readability i would choose example nr. 1 – CodeFanatic Sep 18 '14 at 08:26
  • This really comes down to personal preference and standard practice at whatever organisation you're at. In most situations the difference between the two is only style, and style falls firmly under the guidelines of a coding standards document. – Hecksa Sep 18 '14 at 08:27
  • In simple cases prefer `return condition ? valueA : valueB;` – Jan B. Kjeldsen Sep 18 '14 at 10:24

8 Answers8

4

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.

stealthjong
  • 10,858
  • 13
  • 45
  • 84
  • And now for the reason for the downvote...? – stealthjong Sep 18 '14 at 08:24
  • although it is not explicitly stated in original question, what if you have 3 or more values? Do you nest ternary operators? That gives even worse readability (i didn't downvote) – Kyborek Sep 18 '14 at 08:24
  • @Kyborek no, I almost never nest ternary operators. I'd go with a bunch of if/elses – stealthjong Sep 18 '14 at 08:25
  • 1
    +1 Not sure why this got downvoted - more readable than the other 2 options IMO. – assylias Sep 18 '14 at 08:26
  • I second that, ternary operators are perfectly fine as long as they are not abused, and in many cases do not harm readability at all. A very unjustified down vote. – ethanfar Sep 18 '14 at 08:26
  • Moreover, if you have too many if/else clauses, you probably should have used polymorphism to being with. – ethanfar Sep 18 '14 at 08:37
4

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

CodeFanatic
  • 11,434
  • 1
  • 20
  • 38
2

The code is clearer to read "at a glance" with the else statement there so that is better practice.

Alternatively some (but not all) coding guidelines say that you should only return once at the end of the method. In that case you would have a "to return" value, set that accordingly within the if (which would need an else in this case) and then return that value at the end of the method.

Tim B
  • 40,716
  • 16
  • 83
  • 128
1

The else statement provides more clarity the condition flow, you can adopt the first snippet and no one would blame you but it would be better to reveal your itereations flow base on condition blocks.

I would even suggest to use an aux int value to store the returened result in, then use a single return statement and that would for sure provide more clarity if you care about developers that would land in and review your sources:

public int test(boolean condition)
{
  int valueA = 3;
  int valueB = 5;
  int result;
  if (condition == true) 
  {
    result = valueA;
  }
  else
  {
    result = valueB;
  }

  return result;
}

As an alternative, I would advice the ternary expression mentioned by @stealthjong in his answer since it is more readble when the condition short and no nested instructions are witten in second and third params.

Community
  • 1
  • 1
tmarwen
  • 15,750
  • 5
  • 43
  • 62
0

See both work in same way but there is only one difference your lines code will be less in second one. If you take my advice, I personally follow the second one when it comes to these kind of condition(s). or you can use this one.

return condition ? valueA : valueB;
Qadir Hussain
  • 1,263
  • 1
  • 10
  • 26
  • The example was really meant to be just a generic example where there are only 2 different things to do based on the condition, so the length of the code could vary by quite a bit in an actual method, but thatnks anyway. – Cal Banders Sep 18 '14 at 10:16
0

I say yes, although I have grown the habit of doing so. Programming is very repetitive and practices become habitual. Using the else statement is more efficient, clean if anything.

CodyW
  • 1
  • 2
0

I preper to use if-else statement while returning a value in each block when the line number of method is not more than 10.

However if there is 30 or more line , it is hardly read if-else statements so using just return value instead of using else value could be better.

Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141
0

I would suggest using if-else block (the first approach) because it increases the readability. However for considering performance i had sampled your two approaches in a program. The code is as follows.

public class test {
public static void main(String args[])
{
    int count1=0,count2=0;

    for(int i=0;i<50000;i++)
    {


    long timeStart=System.nanoTime();
    method1(false);
    long timeEnd=System.nanoTime();
    long result1=timeEnd-timeStart;
    System.out.println("\n\nTime taken for method 1 is :"+result1);



    long Start=System.nanoTime();
    method2(false);
    long End=System.nanoTime();
    long result2=End-Start;

    System.out.println("Time taken for method 2 is :"+result2);

    if(result1>result2)
    {
        //increment count2 when result2's execution speed is high (i.e) less time
        count2++;
    }
    if(result1<result2)
    {
        //increment count1 when result1's execution speed is high

        count1++;
    }
    }

    System.out.println("\n\ncount1 value at the end is\t"+count1);
    System.out.println("count2 value at the end is\t"+count2);

}



public static int method1(boolean condition)
{
    int valueA = 3;
    int valueB = 5;
    if (condition == true) {
    return valueA;
    }
    else 
    {
    return valueB;
    }
}


public static int method2(boolean condition)
{
    int valueA = 3;
    int valueB = 5;
    if (condition == true) {
    return valueA;
    }
    return valueB;
}
}

Output:

Testcase 1:

count1 value at the end is 10707 count2 value at the end is 10977

   Testcase 2:

count1 value at the end is 10310 count2 value at the end is 10225

Testcase 3:

count1 value at the end is 9590 count2 value at the end is 10445

Testcase 4:

count1 value at the end is 10687 count2 value at the end is 10435

 Testcase 5:

count1 value at the end is 10670 count2 value at the end is 10223

 Testcase 6:

count1 value at the end is 10594 count2 value at the end is 10810

     Overall cumulative result of all 6 test cases is count1 =62558  count2=63115

so there is no much difference in terms of performance on both approaches. So better thing is to use if else block as it gives equal performance (in terms of time) and increases readability.