Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make large if-statement more readable

Is there a better way for writing a condition with a large number of AND checks than a large IF statement in terms of code clarity?

Eg I currently need to make a field on screen mandatory if other fields do not meet certain requirements. At the moment I have an IF statement which runs over 30 LOC, and this just doesn't seem right.

if(!(field1 == field2 &&
     field3 == field4 &&
     field5 == field6 &&
     .
     .
     .
     field100 == field101))
{
   // Perform operations
}

Is the solution simply to break these down into smaller chunks and assign the results to a smaller number of boolean variables? What is the best way for making the code more readable?

Thanks

like image 393
Longball27 Avatar asked Jul 22 '10 14:07

Longball27


1 Answers

I would consider building up rules, in predicate form:

bool FieldIsValid() { // condition }
bool SomethingElseHappened() { // condition }
// etc

Then, I would create myself a list of these predicates:

IList<Func<bool>> validConditions = new List<Func<bool>> {
  FieldIsValid,
  SomethingElseHappend,
  // etc
};

Finally, I would write the condition to bring forward the conditions:

if(validConditions.All(c => c())
{
  // Perform operations
}
like image 197
Brian Genisio Avatar answered Sep 30 '22 14:09

Brian Genisio