Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an If-Else Statement for a method return, should an Else be explicitly stated if it can instead be implicitly followed?

I have a method that checks certain things and returns a Boolean based on those checks. It involves a single branching If section that checks about 5 conditions in sequence. If any of those conditions return true, then the method will return true;. If none of the conditions return true, then the method will return false;. Since the code after the If section will only run if none of the conditions are true, then that code is logically identical to including an actual Else statement.

So is it a better idea to actually write in the Else statement for this kind of situation?

EDIT

It turns out that I needed information on which condition actually tripped the "true" for some of these, so I changed the method to return an int, with -1 representing the "false" situation. The logic still remains, if none of the conditions are true, it'll return -1. So, I no longer have the condensable option of return (cond1 || cond2 || cond3 || cond4 || cond5);, but I thank everyone for that suggestion too, since I had indeed not thought about it (primarily because cond3 is a very complex condition involving checking for intersection in the midpoints of two pairs of DateTime objects, so it would look ugly). While the nature of the method has changed, the nature of this question has not and all answers are still basically applicable...

The code is currently, to paraphrase it and cut out all the extraneous code that defines cond1 thru cond5...

if (cond1) { return 1; }
else if (cond2) { return 2; }
else if (cond3) { return 3; }
else if (cond4) { return 4; }
else if (cond5) { return 5; }
like image 667
Grace Note Avatar asked Apr 20 '10 16:04

Grace Note


2 Answers

It's really a matter of style and what you (and those you work with) find to be clearer. In general, I personally find the structure:

if( a )
   someResult = doSomething();
else if( b )
   someResult = doSomethingElse();
else
   someResult = doSomethingAnyways();

return someResult;

clearer than:

if( a )
    return doSomething();
if( b )
    return doSomethingElse();
return doSomethingAnyways();
like image 126
LBushkin Avatar answered Oct 24 '22 19:10

LBushkin


I tend to prefer something like this to returning hard values.

static bool SomeFunc(string arg)
{
    bool result = false;

    if (arg.Length < 10)
    {
        result = true;
    }
    else if (arg.StartsWith("foo"))
    {
        result = true;
    }

    if (!result && arg.EndsWith("foo"))
    {
        result = true;
    }

    return result;
}
like image 23
Felan Avatar answered Oct 24 '22 20:10

Felan