mardi 30 juin 2015

Ifs, else ifs and multiple returns

This is not a question about chained ifs or ifs and else ifs. I've seen quite a few of those questions posted in SO already.

My question is also not about performance, its more about coding standards and readability.

Consider the following trivial pseudocode I'm seeing a lot in a project I'm working in:

if (expression > 0)
{
    return 1;
}
else if (expression < 0)
{
    return -1;
}
else
{
    return 0;
}

I usually write this kind of construct in a slightly different way:

if (expression > 0)
{
    return 1;
}

if (expression < 0)
{
    return -1;
}

return 0;

And of course there is the third option that goes by the rule that no method should have more than one return statement which I find too restrictive and cumbersome when the complexity of the method is low:

int retVal;

if (expression > 0)
{
    retVal = 1;
}
else if (expression < 0)
{
    retVal = -1;
}
else
{
    retVal = 0;
}

return retVal;

Is one of options listed above more correct when writing these type of constructs? Performance wise I know the choice is completely irrelevant but from a readability point of view I kind of prefer avoiding the if - else if statements. That said, many co-workers don't agree with me even though they can't give me any convincing arguments.

Aucun commentaire:

Enregistrer un commentaire