How should I rewrite a very large compound if statement in C#?

Michael Broschat picture Michael Broschat · Jun 8, 2009 · Viewed 18.3k times · Source

In my C# code, I have an if statement that started innocently enough:

if((something == -1) && (somethingelse == -1) && (etc == -1)) {
    // ...
}

It's growing. I think there must be 20 clauses in it now.

How should I be handling this?

Answer

user1228 picture user1228 · Jun 8, 2009

Use gates where possible.

the if statement

if(bailIfIEqualZero != 0 && 
   !string.IsNullOrEmpty(shouldNeverBeEmpty) &&
   betterNotBeNull != null &&
   !betterNotBeNull.RunAwayIfTrue &&
   //yadda

the refactored version

if(bailIfIEqualZero == 0)
  return;

if(string.IsNullOrEmpty(shouldNeverBeEmpty))
  return;

if(betterNotBeNull == null || betterNotBeNull.RunAwayIfTrue)
  return;

//yadda