0

I have a string typeStringwhich I'm trying to parse to an Enum with 30 cases, all of which have rather unique return statements. In some books I have seen a control flow like this used

if (!Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
    Log.Error("Unknown Replicating instrument type: " + typeString);
    return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
switch (replicatingInstrumentType)
{
    case TypeA:
    {
        return TypeAReturnStatement;
    }

    // .....
    // more cases here ....
    // .....

    case TypeZ:
    {
        return TypeZReturnStatement;
    }
    default:
    {
        return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
    }
}

whereas I've always figured one should do

if (Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
    switch (replicatingInstrumentType)
    {
        case TypeA:
            {
                return TypeAReturnStatement;
            }

        // .....
        // more cases here ....
        // .....

        case TypeZ:
            {
                return TypeZReturnStatement;
            }
        default:
            {
                return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
            }
    }
}

Log.Error("Unknown Replicating instrument type: " + typeString);
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);

Besides the visual diference, is there any advantage/disadvantage over using one versus the other? Is there a consensus on which approach is better?

HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34

1 Answers1

2
if (!Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
    Log.Error("Unknown Replicating instrument type: " + typeString);
    return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}

Its called Inverted IF or Replace Nested Conditional with Guard Clauses. Its just for easier readabilty as it reduces the number of nesting and indentation. Lesser the indentation increases your horizontal view area.

Carbine
  • 7,849
  • 4
  • 30
  • 54
  • Personally, I hate this....but well, it's an opinion... – Liam Feb 23 '16 at 14:50
  • 1
    @Liam I hate when I find conditionals nested 3,4,5 levels deep when a few easy-to-find, easy-to-read guard statements could have just been placed at the top of the method. Likewise, just an opinion. To each their own. Either way, **consistency is the important issue here**. – Dan Bechard Feb 23 '16 at 14:53
  • There are no winners here... :) – Liam Feb 23 '16 at 15:04