+25  A: 

You should do whatever makes the code clearer.

Russ
That's also the correct answer for about 99% of programming
Martin Beckett
A: 

In this case just return the expression result directly.

return (a != 0)

But in general I try to avoid having returns from the middle of a function. Have one return per function.

Brian Ensink
If the function is in a loop and called thousands of times, wouldn't returning when you know the result be faster?
stagas
Why do you limit yourself to one return statement per function? I see no reason to do that.
Hammerite
`Have one return per function.` this can lead to very messy, confusing methods. Abstract it and think 'what am i trying to achieve by having one return per method?' - cleaner, understandable code.
rmx
If "result is known" is one of the exit conditions of the loop it should be in the loop expression instead of embedded in a IF statement and returning from the middle of the loop.
Brian Ensink
@Hammerite Its just a general rule. Sometimes a few more returns can produce clearer code. But "too many" returns and it becomes more difficult to read that code N days from now.
Brian Ensink
You advocate clearer code, but you also say in response to stagas that "If 'result is known' is one of the exit conditions of the loop it should be in the loop expression". Isn't that approach a recipe for long, unwieldy loop expressions that aren't clear at all?
Hammerite
@Hammerite Of course clearer code wins. A loop with exit conditions throughout is equally a recipe for long, unwieldy loop bodies that aren't clear at all. Hence you have to make a judgement call.
Brian Ensink
OK, well I can agree that there is always a need to be pragmatic and emphasise clarity. Part of imposing a rule is knowing when to break that rule.
Hammerite
A bunch of early exits for edge conditions can avoid a metric ton of unnecessary processing. (e.g. complex sorting algorithms with huge overhead called on empty, single entry and two-entry sources)
deworde
+17  A: 

It gets optimized at compile time anyway, so no runtime difference.

As usual, you can argue about style. My 50 cents: the first variant (no explicit else) is nicer because it's less code doing exactly the same.

Of course, in this case, you would do

return a != 0;

... but I think the question is meant to be general.

Michael
Someone actually answering the question rather than trying to solve the *example*
Noel M
I can envision a case in C where the else actually results in slightly more code generated if optimization is not enabled - i.e. the first return might be followed by an unreachable jump around the else clause :-)
phkahler
I would code an empty else clause and the return false at the end of the function - it makes it clear you have though about the else, the next programmer will add code in the right place and the empty else will be optimized away
Martin Beckett
Nice thoughts, Martin, never thought of it like this. I generally try to avoid empty blocks, and would think "there's something missing" if someone leaves me with an empty else {} ... but now I know what it could mean. Guess you never stop learning :)
Michael
+2  A: 
if(statement)
       result = true
else
       result = false

return result
Dominique
Why not just "return statement;" ?
mbeckish
@mbeckish: in the specific example given in the question you would indeed just return the result of statement. However, the question was meant to address the general case where there may be lots of code between the if and else.
Bryan Oakley
@mbeckish, Bryan is right, this code is meant to be general, this same syntax would work also with any type of value returned.
Dominique
+6  A: 

I would say it's a good practice to do so, because it would make changing the code a bit easier. For instance, let's say you wanted to print out the result. You could either change it like this:

if (a != 0) {
    print "returning true"
    return true
}
print "returning false"
return false

Which means adding a print twice, or else:

if (a != 0) {
    retval = true
} else {
    retval = false
}

print "returning ", retval
return retval

which means adding one print, but this won't work without the else.

Of course, this is a contrived example, but it shows how you should try to make your code as maintainable as possible.

Nathan Fellman
Your code doesn't even compile! The if statement is just plain wrong!
Noel M
@Noel: fixed. anyway, this question is tagged "language-agnostic". Maybe in the language I wrote it in, `(a !=)` is shorthand for `(a != 0)`.
Nathan Fellman
Apologies - didn't see the agnostic tag - don't know what I was actually thinking
Noel M
Incidentally, this is a good example of using a single return statement.
blizpasta
+2  A: 

Both would work the same in most languages, but I'd think using else would be best to make it more obvious that when none of the if/else if statements above are true, then do this, even though this obviously isn't necessary.
But, however, if you have a lot of code below the if statement, then you shouldn't do this, since it would only become a huge mess with a lot of unnecessary else statements.

Frxstrem
good point about all the code below the `if`
Nathan Fellman
+3  A: 

As the compiler will probably reduce it to the same compiled code anyway, do what you believe to be more "beautiful".

Note that code elegance is subjective, so dogmatically clinging to one format or another is unnecessary.

kbrimington
+1  A: 

I would tend to not use the else if it is superfluous, any developer should understand what is going to happen:

public void DoSomethingConditionally(Foo foo)
{
    if (Bar)
    {
        foo.DoX();
        return;
    }
    foo.DoY();
}

I disagree with people who want only one return point per function, your functions should be small and a few return points enhance rather than hinder readability.

Ian Johnson
+2  A: 

If the language requires braces for if/else statements, I personally like to remove the else statement and the accompanying braces. The intention of the code will be just as clear, but the code will be less indented, which (usually) improves readability.

As others mentioned, the compiler will optimize the else statement. But if you're dealing with an interpreted language, the else statement has to be interpreted. In that case removing it will result in a minor (very minor) performance increase.

Niels van der Rest
I think he wrote in some language that doesn't need braces. It's tagged *language-agnostic*
Nathan Fellman
@Nathan: You're right, my answer was too language-specific, I've updated it.
Niels van der Rest
A: 

IMO - If your intention is to return true when some condition is met, (e.g. something is found), and then maybe process the data other way, and at last, when nothing is found, return false, the option without else is clearer.

If your return value depends only on the condition in if, the if-else variant looks better.

Yossarian
A: 

It doesn't matter. The compiler will turn out the same code either way. Check to see what convention existing code follows, and then just do the same.

Personally I don't put the "else" because it's obvious. I find that the extra "else" looks cluttered.

Ripter
A: 

I personally like the Syntax:

/*Function header comments*/
Function(...)
{ 
  /*English what the if is trying to achieve*/
  If(...)
  {
    ...
    Return True; /*What this tells me*/
  }
  Else
  {
    ...
    Return False: /*What this tells me*/
  }
}

Simply because I find myself in the situation if I simply do

If(...)
Return True;
Else
Return False;

or

If(...)
Return True;

Return False;

or

(...)?Return True:Return False;

That it's not as clear,even though with the right comment the one liner is cool, and if I'm doing a comparison anyways there is a good chance that down the road I may think of something that needs to happen in that area anyways, I mean I'm doing an if for more than grins. Also if I find a special case that needs an Else If its just a matter of adding in the Else If portions.

Cericme
A: 
function DoSomethingConditionally(foo)
{
    if (Bar)
    {
        foo.DoX();
        return;
    }
    else
    {
        foo.DoY();
    }
}

I like this style, just in case I need to add something later.

timw4mail
Why bother when [you ain't gonna need it?](http://en.wikipedia.org/wiki/YAGNI) :p
meagar
Consistency, consistency, consistency.
timw4mail
+2  A: 

Of course "else" should be declared explicitly.

There are several reasons why 'else' should be declared explicitly :

  1. Readability
    I won't sacrifice readability for some "cool" programming style. But, i will understand if you're facing bandwith-oriented problem like minifying javascript.
  2. Conceptual. Your first code doesn't tell the human reader "what will you do if the 'if guard' returns false". Instead, your code tells the reader that "default value is false, true only happens when bla-bla-bla". Or in another word, your code tells the reader that "I assume the value is false, it's true only when bla-bla-bla".

On the conceptual reason above, it - of course - depends on your function specification. For some function it makes sense to use such code. For example "Function assumes the visitor is not registered, he is only registered only if bla-bla-bla".

But for another problem like "If a number is divisible by two then it is even otherwise odd", you should write it explicitly so that a reader (perhaps not a programmer) will not be confused when reading your code. Since the reader (maybe a mathematician) only knows such invariant and he/she only knows a little about programming language.

jancrot
A: 

My decision whether or not to use the "else" depends upon my semantic interpretation of the "if" and, in some cases, the return value. In cases where I feel the "if" is deciding between two courses of action or two return values, I will use the "else". In cases where I feel it's deciding between acting normally and "aborting early", I'll skip the else. In cases where the return value answers the question, "Did something fail", I'll generally regard an error return as an early abort, even if the only remaining thing to do would be return success, and thus skip the "else". If, however, the return value asks, "Is something xxx", then I'll far more often include the "else".

supercat
+1  A: 

Just stick in an else and move on to something more exciting!

AJM
A: 

The example is overly simplistic. Most of the answers are advocating a coding short-cut which dodges the true question about logic branches. The compiler may optimize out the else branch so that it is logically equivalent to not using the else branch, but why make the compiler work more? If this is a scripting language that gets compile often, there's no reason to add the extra "else".

Also, source code analyzers will not optimize this out. The extra "else" will count as another logic branch. This might make your functions more "complex" than they are. See "CRAP Index", "Cyclomatic Complexity", and other software metrics.

http://en.wikipedia.org/wiki/Cyclomatic_complexity

If both of the following examples get compiler optimized to the same byte-code, pick whichever style suits you and stick to it. Personally, I feel the first example is more maintainable.

public void DoSomethingConditionally(Foo foo)
{
    if (Bar)
    {
        foo.DoX();
        return;
    }
    if (Baz)
    {
        foo.DoZ();
        return;
    }

    foo.DoY();
}



public void DoSomethingConditionally(Foo foo)
{
    if (Bar)
    {
        foo.DoX();
    }
    elseif (Baz)
    {
        foo.DoZ();
    }
    else 
    {
        foo.DoY();
    }
    return;
}
A: 

The LLVM Coding Standards and the Mozilla Coding Style both state that else should not be used after a return.

Kevin Stock