0

Should you write your functions like this:

int foo()
{
    if (bar)
        return 1;
    return 2;
}

Or like this?

int foo()
{
    if (bar)
        return 1;
    else
        return 2;
}

Is one way objectively better than the other, or is it a matter of personal preference? If one way is better, why?

  • It is a matter of personal preference. – Thilo Apr 21 '16 at 02:46
  • Related: http://stackoverflow.com/questions/27024084/is-there-a-performance-difference-between-returning-inside-if-block-or-writing?rq=1 http://stackoverflow.com/questions/26003104/java-best-style-for-return-statement-inside-or-outside-if-condition?rq=1 http://stackoverflow.com/questions/32824797/different-design-decisions-with-if-else-statements?rq=1 – Thilo Apr 21 '16 at 02:48
  • 1
    Note that there also is `return bar ? 1 : 2` – Thilo Apr 21 '16 at 02:58

3 Answers3

1

I try to have one exit point from a function whenever possible. Makes the code more maintainable and debugable. So I'd do something like this:

int foo()
{
    var retVal;
    if (bar) {
        retVal = 1;
    }
    else {
        retVal = 2;
    }
    return retVal;
}

Or this if you want to be more concise...

int foo()
{
    var retVal = 2;
    if (bar) {
        retVal = 1;
    }
    return retVal;
}
RJM
  • 1,164
  • 9
  • 21
  • @Reddy - How is it unreachable? It will always be executed. – RJM Apr 21 '16 at 02:52
  • `return retVal;` is unreachable.. if the control goes inside if then the return statement inside if will get executed. else if it skips if the return statement in else will get executed. There is no other flow available.. you syntax would be good if its `if` `else if` ... – Rajshekar Reddy Apr 21 '16 at 02:54
  • @Reddy - You've lost me....there is no return statement in the `if`, nor is there a return statement in the `else`. The only return statement is the last statement. – RJM Apr 21 '16 at 02:55
1

Nothing different in the matter of performance. Here Its personal preference. I prefer the second one as it is clean and understandable. Experienced folks can grasp both the syntax right away But when you place the first syntax in front of a new programmer he will get confused.

I prefer neat code (keeping into account both readability and performance). When there is certainly no performance improvement with the first syntax I would choose second syntax.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
0

there is no performance improvement in any of the statements above and totally your choice. compiler is smart enough to figure out what you are trying to do. personally i prefer the first one because that means less code. however in c#, msil generated will be the same for both scenarios.

Baahubali
  • 4,604
  • 6
  • 33
  • 72