Search code examples
coding-style

if (condition) continue; OR if (!condition) { ... }? (style preference)


I know this is a matter of style, hence the subjective tag. I have a small piece of code, with two nested conditions. I could code it in two ways, and I'd like to see how more experienced developers think it should look like.

Style 1:

while (!String.IsNullOrEmpty(msg = reader.readMsg()))
{
    RaiseMessageReceived();
    if (parseMsg)
    {
        ParsedMsg parsedMsg = parser.parseMsg(msg);
        RaiseMessageParsed();
        if (processMsg)
        {
            process(parsedMsg);
            RaiseMessageProcessed();
        }
    }
}

Style 2:

while (!String.IsNullOrEmpty(msg = reader.readMsg()))
{
    RaiseMessageReceived();
    if (!parseMsg) continue;

    ParsedMsg parsedMsg = parser.parseMsg(msg);
    RaiseMessageParsed();
    if (!processMsg) continue;

    process(parsedMsg);
    RaiseMessageProcessed();
}

(Side question: how do I put empty lines in the source code sample?)


Solution

  • In principle I agree with the majority who prefer style 1. This is what Steve Mcconnell endorses in "Code Complete" - say what you mean, i.e. if you are more interested in the condition being true, while the false state is rarer or not preferred, then state the preferred version.

    In practice though I often find myself using style 2, because I like to weed out all the possible error / invalid states first. After I get rid of all the possibilities I am not interested in, I can write the heart-of-the-matter code down to the end of the routine without constantly wondering if I need to guard against some condition or other. Basically, the attitude is, get rid of the chaff, then do the real work in peace.