Search code examples
c#design-patternsif-statementcode-readability

Is there a more readable way of making a long chain of && statements?


Suppose I have a long, complex list of conditions, which must be true in order for an if statement to run.

if(this == that && foo != bar && foo != that && pins != needles && apples != oranges)
{
    DoSomethingInteresting();
}

Typically, if I'm forced into doing something like this, I'll just put each statement on its own line, like this:

if
(
         this == that 
    &&    foo != bar 
    &&    foo != that 
    &&   pins != needles 
    && apples != oranges
)
{
    DoSomethingInteresting();
}

But I still feel this is a bit of a mess. I'm tempted to refactor the contents of the if statement into its own property like this

if(canDoSomethingInteresting)
{
    DoSomethingInteresting();
}

But then that just moves all the mess into canDoSomethingInteresting() and doesn't really fix the problem.

As I said, my goto solution is the middle one, because it doesn't obfuscate the logic like the last one and is more readable than the first. But there must be a better way!

Example in response to Sylon's comment

bool canDoSomethingInteresting
{
    get{
        //If these were real values, we could be more descriptive ;)
        bool thisIsThat = this == that;
        bool fooIsntBar = foo != bar;
        bool fooIsntThat = foo != that;
        return 
        (
               thisIsThat
            && fooIsntBar
            && fooIsntThat
        );
    }
}
if(canDoSomethingInteresting)
{
    DoSomethingInteresting();
}

Solution

  • In my opinion moving the mess into a Property or a Method is not that bad an idea. That way it is self contained and your main logic where you do the if(..) check becomes more readable. Especially if the list of conditions to check is huge, it is better off being in a property, that way if you need to re-use that you are not duplicating that check.

    if(IsAllowed)
    {
       DoSomethingInteresting();
    }