<p>It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life.</p>

<p>Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem?</p>

<p>Example, all on one line:</p>

<pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true &amp;&amp; var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true)
{
</code></pre>

<p>Example, multi-line:</p>

<pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true
 &amp;&amp; var3 = true &amp;&amp; var4 = true &amp;&amp; var5 = true
 &amp;&amp; var6 = true)
{
</code></pre>

<p>Example-nested:</p>

<pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true)
{
     if (var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true)
     {
</code></pre>

[{'answer_id': 6131, 'author': 'abyx', 'author_id': 573, 'author_profile': 'https://Stackoverflow.com/users/573', 'pm_score': 3, 'selected': False, 'text': '<p>First, I\'d remove all the <code>== true</code> parts, that would make it 50% shorter ;)</p>\n\n<p>When I have big condition I search for the reasons. Sometimes I see I should use polymorphism, sometimes I need to add some state object. Basically, it implies a refactoring is needed (a code smell). </p>\n\n<p>Sometimes I use <a href="http://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow noreferrer">De-Morgan\'s laws</a> to simplify boolean expressions a bit.</p>\n'}, {'answer_id': 6132, 'author': 'TimM', 'author_id': 32, 'author_profile': 'https://Stackoverflow.com/users/32', 'pm_score': 1, 'selected': False, 'text': '<p>I resort to separate boolean values:</p>\n\n<pre><code>Bool cond1 == (var1 &amp;&amp; var2);\nBool cond2 == (var3 &amp;&amp; var4);\n\nif ( cond1 &amp;&amp; cond2 ) {}\n</code></pre>\n'}, {'answer_id': 6133, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 2, 'selected': False, 'text': "<p>I've seen a lot of people and editors either indenting each condition in your if statement with one tab, or matching it up with the open paren:</p>\n\n<pre><code>if (var1 == true\n    &amp;&amp; var2 == true\n    &amp;&amp; var3 == true\n   ) {\n    /* do something.. */\n}\n</code></pre>\n\n<p>I usually put the close paren on the same line as the last condition:</p>\n\n<pre><code>if (var1 == true\n    &amp;&amp; var2 == true\n    &amp;&amp; var3 == true) {\n    /* do something.. */\n}\n</code></pre>\n\n<p>But I don't think this is quite as clean.</p>\n"}, {'answer_id': 6135, 'author': 'Mike Powell', 'author_id': 205, 'author_profile': 'https://Stackoverflow.com/users/205', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ll often split these up into component boolean variables:</p>\n\n<pre><code>bool orderValid = orderDate &lt; DateTime.Now &amp;&amp; orderStatus != Status.Canceled;\nbool custValid = customerBalance == 0 &amp;&amp; customerName != "Mike";\nif (orderValid &amp;&amp; custValid)\n{\n...\n</code></pre>\n'}, {'answer_id': 6140, 'author': 'Coincoin', 'author_id': 42, 'author_profile': 'https://Stackoverflow.com/users/42', 'pm_score': 7, 'selected': True, 'text': '<p>Separate the condition in several booleans and then use a master boolean as the condition.</p>\n\n<pre><code>bool isOpaque = object.Alpha == 1.0f;\nbool isDrawable = object.CanDraw &amp;&amp; object.Layer == currentLayer;\nbool isHidden = hideList.Find(object);\n\nbool isVisible = isOpaque &amp;&amp; isDrawable &amp;&amp; ! isHidden;\n\nif(isVisible)\n{\n    // ...\n}\n</code></pre>\n\n<p>Better yet:</p>\n\n<pre><code>public bool IsVisible {\n    get\n    {\n        bool isOpaque = object.Alpha == 1.0f;\n        bool isDrawable = object.CanDraw &amp;&amp; object.Layer == currentLayer;\n        bool isHidden = hideList.Find(object);\n\n        return isOpaque &amp;&amp; isDrawable &amp;&amp; ! isHidden;\n    }\n}\n\nvoid Draw()\n{\n     if(IsVisible)\n     {\n         // ...\n     }\n}\n</code></pre>\n\n<p>Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU!</p>\n'}, {'answer_id': 6142, 'author': 'Mark Renouf', 'author_id': 758, 'author_profile': 'https://Stackoverflow.com/users/758', 'pm_score': 2, 'selected': False, 'text': "<p>Well, first off, why not:</p>\n\n<blockquote>\n  <p>if (var1 &amp;&amp; var2 &amp;&amp; var2 &amp;&amp; var3 &amp;&amp; var4 &amp;&amp; var5 &amp;&amp; var6) {<br>\n   ...  </p>\n</blockquote>\n\n<p>Also, it's very hard to refactor abstract code examples. If you showed a specific example it would be easier to identify a better pattern to fit the problem.</p>\n\n<p>It's no better, but what I've done in the past:\n(The following method prevents short-circuiting boolean testing, all tests are run even if the first is false. Not a recommended pattern unless you know you need to always execute all the code before returning -- Thanks to ptomato for spotting my mistake!)</p>\n\n<blockquote>\n  <p>boolean ok = cond1;<br>\n  ok &amp;= cond2;<br>\n  ok &amp;= cond3;<br>\n  ok &amp;= cond4;<br>\n  ok &amp;= cond5;<br>\n  ok &amp;= cond6;  </p>\n</blockquote>\n\n<p><strike>Which is the same as:</strike> (not the same, see above note!)</p>\n\n<blockquote>\n  <p>ok = (cond1 &amp;&amp; cond2 &amp;&amp; cond3 &amp;&amp; cond4 &amp;&amp; cond5 &amp;&amp; cond6);</p>\n</blockquote>\n"}, {'answer_id': 6148, 'author': 'Nicholas Trandem', 'author_id': 765, 'author_profile': 'https://Stackoverflow.com/users/765', 'pm_score': 0, 'selected': False, 'text': '<p>I like to break them down by level, so I\'d format you example like this:</p>\n\n<pre><code>if (var1 = true\n &amp;&amp; var2 = true\n &amp;&amp; var2 = true\n &amp;&amp; var3 = true\n &amp;&amp; var4 = true\n &amp;&amp; var5 = true\n &amp;&amp; var6 = true){\n</code></pre>\n\n<p>It\'s handy when you have more nesting, like this (obviously the real conditions would be more interesting than "= true" for everything):</p>\n\n<pre><code>if ((var1 = true &amp;&amp; var2 = true)\n &amp;&amp; ((var2 = true &amp;&amp; var3 = true)\n  &amp;&amp; (var4 = true &amp;&amp; var5 = true))\n &amp;&amp; (var6 = true)){\n</code></pre>\n'}, {'answer_id': 6152, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 2, 'selected': False, 'text': '<p>Check out <a href="https://rads.stackoverflow.com/amzn/click/com/0321413091" rel="nofollow noreferrer" rel="nofollow noreferrer">Implementation Patterns</a> by Kent Beck.  There is a particular pattern I am thinking of that may help in this situation... it is called "Guards".  Rather than having tons of conditions, you can break them out into a guard, which makes it clear which are the adverse conditions in a method.</p>\n\n<p>So for example, if you have a method that does something, but there are certain conditions where it shouldn\'t do something, rather than:</p>\n\n<pre><code>public void doSomething() {\n    if (condition1 &amp;&amp; condition2 &amp;&amp; condition3 &amp;&amp; condition4) {\n        // do something\n    }\n}\n</code></pre>\n\n<p>You could change it to:</p>\n\n<pre><code>public void doSomething() {\n    if (!condition1) {\n        return;\n    }\n\n    if (!condition2) {\n        return;\n    }\n\n    if (!condition3) {\n        return;\n    }\n\n    if (!condition4) {\n        return;\n    }\n\n    // do something\n}\n</code></pre>\n\n<p>It\'s a bit more verbose, but a lot more readable, especially when you start having weird nesting, the guard can help (combined with extracting methods).</p>\n\n<p>I HIGHLY recommend that book by the way.</p>\n'}, {'answer_id': 6157, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m surprised no one got this one yet. There\'s a refactoring specifically for this type of problem:</p>\n\n<p><a href="http://www.refactoring.com/catalog/decomposeConditional.html" rel="nofollow noreferrer">http://www.refactoring.com/catalog/decomposeConditional.html</a></p>\n'}, {'answer_id': 6158, 'author': 'Simon Gillbee', 'author_id': 756, 'author_profile': 'https://Stackoverflow.com/users/756', 'pm_score': 3, 'selected': False, 'text': '<p>There are two issues to address here: readability and understandability</p>\n\n<p>The "readability" solution is a style issue and as such is open to interpretation. My preference is this:</p>\n\n<pre><code>if (var1 == true &amp;&amp; // Explanation of the check\n    var2 == true &amp;&amp; // Explanation of the check\n    var3 == true &amp;&amp; // Explanation of the check\n    var4 == true &amp;&amp; // Explanation of the check\n    var5 == true &amp;&amp; // Explanation of the check\n    var6 == true)   // Explanation of the check\n    { }\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>if (var1 &amp;&amp; // Explanation of the check\n    var2 &amp;&amp; // Explanation of the check\n    var3 &amp;&amp; // Explanation of the check\n    var4 &amp;&amp; // Explanation of the check\n    var5 &amp;&amp; // Explanation of the check\n    var6)   // Explanation of the check\n    { }\n</code></pre>\n\n<p>That said, this kind of complex check can be quite difficult to mentally parse while scanning the code (especially if you are not the original author). Consider creating a helper method to abstract some of the complexity away:</p>\n\n<pre><code>/// &lt;Summary&gt;\n/// Tests whether all the conditions are appropriately met\n/// &lt;/Summary&gt;\nprivate bool AreAllConditionsMet (\n    bool var1,\n    bool var2,\n    bool var3,\n    bool var4,\n    bool var5,\n    bool var6)\n{\n    return (\n        var1 &amp;&amp; // Explanation of the check\n        var2 &amp;&amp; // Explanation of the check\n        var3 &amp;&amp; // Explanation of the check\n        var4 &amp;&amp; // Explanation of the check\n        var5 &amp;&amp; // Explanation of the check\n        var6);  // Explanation of the check\n}\n\nprivate void SomeMethod()\n{\n    // Do some stuff (including declare the required variables)\n    if (AreAllConditionsMet (var1, var2, var3, var4, var5, var6))\n    {\n        // Do something\n    }\n}\n</code></pre>\n\n<p>Now when visually scanning the "SomeMethod" method, the actual complexity of the test logic is hidden but the semantic meaning is preserved for humans to understand at a high-level. If the developer really needs to understand the details, the AreAllConditionsMet method can be examined.</p>\n\n<p>This is formally known as the "Decompose Conditional" refactoring pattern I think. Tools like Resharper or Refactor Pro! can making doing this kind of refactoring easy!</p>\n\n<p>In all cases, the key to having readable and understandable code is to use realistic variable names. While I understand this is a contrived example, "var1", "var2", etc are <strong>not</strong> acceptable variable names. They should have a name which reflects the underlying nature of the data they represent.</p>\n'}, {'answer_id': 6159, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 0, 'selected': False, 'text': "<p>If you happen to be programming in Python, it's a cinch with the built-in <code>all()</code> function applied over the list of your variables (I'll just use Boolean literals here):</p>\n\n<pre><code>&gt;&gt;&gt; L = [True, True, True, False, True]\n&gt;&gt;&gt; all(L) # True, only if all elements of L are True.\nFalse\n&gt;&gt;&gt; any(L) # True, if any elements of L are True.\nTrue\n</code></pre>\n\n<p>Is there any corresponding function in your language (C#? Java?). If so, that's likely the cleanest approach.</p>\n"}, {'answer_id': 6163, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': -1, 'selected': False, 'text': "<p>If you do this:</p>\n\n<pre><code>if (var1 == true) {\n    if (var2 == true) {\n        if (var3 == true) {\n            ...\n        }\n    }\n}\n</code></pre>\n\n<p>Then you can also respond to cases where something isn't true. For example, if you're validating input, you could give the user a tip for how to properly format it, or whatever.</p>\n"}, {'answer_id': 6178, 'author': 'TimM', 'author_id': 32, 'author_profile': 'https://Stackoverflow.com/users/32', 'pm_score': 0, 'selected': False, 'text': "<p>McDowell,</p>\n\n<p>You are correct that when using the single '&amp;' operator that both sides of the expression evaluate.  However, when using the '&amp;&amp;' operator (at least in C#) then the first expression to return false is the last expression evaluated.  This makes putting the evaulation before the FOR statement just as good as any other way of doing it.</p>\n"}, {'answer_id': 6187, 'author': 'Kevin', 'author_id': 40, 'author_profile': 'https://Stackoverflow.com/users/40', 'pm_score': 1, 'selected': False, 'text': "<p>As others have mentioned, I would analyze your conditionals to see if there's a way you can outsource it to other methods to increase readability.</p>\n"}, {'answer_id': 6193, 'author': 'fastcall', 'author_id': 328, 'author_profile': 'https://Stackoverflow.com/users/328', 'pm_score': 0, 'selected': False, 'text': '<p>@tweakt</p>\n\n<blockquote>\n  <p>It\'s no better, but what I\'ve done in the past:</p>\n  \n  <p>boolean ok = cond1;\n     ok &amp;= cond2;\n     ok &amp;= cond3;\n     ok &amp;= cond4;\n     ok &amp;= cond5;\n     ok &amp;= cond6;</p>\n  \n  <p>Which is the same as:</p>\n  \n  <p>ok = (cond1 &amp;&amp; cond2 &amp;&amp; cond3 &amp;&amp; cond4 &amp;&amp; cond5 &amp;&amp; cond6);</p>\n</blockquote>\n\n<p>Actually, these two things are not the same in most languages.  The second expression will typically stop being evaluated as soon as one of the conditions is false, which can be a big performance improvement if evaluating the conditions is expensive.</p>\n\n<p>For readability, I personally prefer Mike Stone\'s proposal above.  It\'s easy to verbosely comment and preserves all of the computational advantages of being able to early out.  You can also do the same technique inline in a function if it\'d confuse the organization of your code to move the conditional evaluation far away from your other function.  It\'s a bit cheesy, but you can always do something like:</p>\n\n<pre><code>do {\n    if (!cond1)\n       break;\n    if (!cond2)\n       break;\n    if (!cond3)\n       break;\n    ...\n    DoSomething();\n} while (false);\n</code></pre>\n\n<p>the while (false) is kind of cheesy.  I wish languages had a scoping operator called "once" or something that you could break out of easily.</p>\n'}, {'answer_id': 14148, 'author': 'Brian', 'author_id': 700, 'author_profile': 'https://Stackoverflow.com/users/700', 'pm_score': 2, 'selected': False, 'text': '<p>Try looking at Functors and Predicates.  The Apache Commons project has a great set of objects to allow you to encapsulate conditional logic into objects.  Example of their use is available on O\'reilly <a href="http://www.onjava.com/pub/a/onjava/2004/12/22/jakarta-gems-1.html?page=2" rel="nofollow noreferrer">here</a>.  Excerpt of code example:</p>\n\n<pre><code>import org.apache.commons.collections.ClosureUtils;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.collections.functors.NOPClosure;\n\nMap predicateMap = new HashMap();\n\npredicateMap.put( isHonorRoll, addToHonorRoll );\npredicateMap.put( isProblem, flagForAttention );\npredicateMap.put( null, ClosureUtils.nopClosure() );\n\nClosure processStudents = \n    ClosureUtils.switchClosure( predicateMap );\n\nCollectionUtils.forAllDo( allStudents, processStudents );\n</code></pre>\n\n<p>Now the details of all those isHonorRoll predicates and the closures used to evaluate them:</p>\n\n<pre><code>import org.apache.commons.collections.Closure;\nimport org.apache.commons.collections.Predicate;\n\n// Anonymous Predicate that decides if a student \n// has made the honor roll.\nPredicate isHonorRoll = new Predicate() {\n  public boolean evaluate(Object object) {\n    Student s = (Student) object;\n\n    return( ( s.getGrade().equals( "A" ) ) ||\n            ( s.getGrade().equals( "B" ) &amp;&amp; \n              s.getAttendance() == PERFECT ) );\n  }\n};\n\n// Anonymous Predicate that decides if a student\n// has a problem.\nPredicate isProblem = new Predicate() {\n  public boolean evaluate(Object object) {\n    Student s = (Student) object;\n\n    return ( ( s.getGrade().equals( "D" ) || \n               s.getGrade().equals( "F" ) ) ||\n             s.getStatus() == SUSPENDED );\n  }\n};\n\n// Anonymous Closure that adds a student to the \n// honor roll\nClosure addToHonorRoll = new Closure() {\n  public void execute(Object object) {\n    Student s = (Student) object;\n\n    // Add an award to student record\n    s.addAward( "honor roll", 2005 );\n    Database.saveStudent( s );\n  }\n};\n\n// Anonymous Closure flags a student for attention\nClosure flagForAttention = new Closure() {\n  public void execute(Object object) {\n    Student s = (Student) object;\n\n    // Flag student for special attention\n    s.addNote( "talk to student", 2005 );\n    s.addNote( "meeting with parents", 2005 );\n    Database.saveStudent( s );\n  }\n};\n</code></pre>\n'}, {'answer_id': 14167, 'author': 'wusher', 'author_id': 1632, 'author_profile': 'https://Stackoverflow.com/users/1632', 'pm_score': 0, 'selected': False, 'text': '<p>I like to break each condition into descriptive variables.</p>\n\n<pre><code>bool isVar1Valid, isVar2Valid, isVar3Valid, isVar4Valid;\nisVar1Valid = ( var1 == 1 )\nisVar2Valid = ( var2.Count &gt;= 2 )\nisVar3Valid = ( var3 != null )\nisVar4Valid = ( var4 != null &amp;&amp; var4.IsEmpty() == false )\nif ( isVar1Valid &amp;&amp; isVar2Valid &amp;&amp; isVar3Valid &amp;&amp; isVar4Valid ) {\n     //do code\n}\n</code></pre>\n'}, {'answer_id': 14220, 'author': 'Yuval F', 'author_id': 1702, 'author_profile': 'https://Stackoverflow.com/users/1702', 'pm_score': 2, 'selected': False, 'text': '<p>Steve Mcconell\'s advice, from <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">Code Complete</a>:\nUse a multi-dimensional table. Each variable serves as an index to the table,\nand the if statement turns into a table lookup. For example if (size == 3 &amp;&amp; weight > 70)\ntranslates into the table entry decision[size][weight_group]</p>\n'}, {'answer_id': 202845, 'author': 'Brad Gilbert', 'author_id': 1337, 'author_profile': 'https://Stackoverflow.com/users/1337', 'pm_score': 0, 'selected': False, 'text': '<p>If I was doing it in Perl, This is how I might run the checks.</p>\n\n<pre><code>{\n  last unless $var1;\n  last unless $var2;\n  last unless $var3;\n  last unless $var4;\n  last unless $var5;\n  last unless $var6;\n\n  ... # Place Code Here\n}\n</code></pre>\n\n<p>If you plan on using this over a subroutine replace every instance of <code>last</code> with <code>return</code>;</p>\n'}, {'answer_id': 2797562, 'author': 'Milan Babuškov', 'author_id': 14690, 'author_profile': 'https://Stackoverflow.com/users/14690', 'pm_score': 1, 'selected': False, 'text': "<p>In reflective languages like PHP, you can use variable-variables:</p>\n\n<pre><code>$vars = array('var1', 'var2', ... etc.);\nforeach ($vars as $v)\n    if ($$v == true) {\n        // do something\n        break;\n    }\n</code></pre>\n"}, {'answer_id': 43766233, 'author': 'Sean', 'author_id': 7892369, 'author_profile': 'https://Stackoverflow.com/users/7892369', 'pm_score': 0, 'selected': False, 'text': '<pre><code>    if (   (condition_A)\n        &amp;&amp; (condition_B)\n        &amp;&amp; (condition_C)\n        &amp;&amp; (condition_D)\n        &amp;&amp; (condition_E)\n        &amp;&amp; (condition_F)\n       )\n    {\n       ...\n    }\n</code></pre>\n\n<p>as opposed to</p>\n\n<pre><code>    if (condition_A) {\n       if (condition_B) {\n          if (condition_C) {\n             if (condition_D) {\n                if (condition_E) {\n                   if (condition_F) {\n                      ...\n                   }\n                }\n             }\n          }\n       }\n    }\n</code></pre>\n\n<p>and</p>\n\n<pre><code>    if (   (   (condition_A)\n            &amp;&amp; (condition_B)\n           )\n        || (   (condition_C)\n            &amp;&amp; (condition_D)\n           )\n        || (   (condition_E)\n            &amp;&amp; (condition_F)\n           )\n       )\n    {\n       do_this_same_thing();\n    }\n</code></pre>\n\n<p>as opposed to</p>\n\n<pre><code>    if (condition_A &amp;&amp; condition_B) {\n       do_this_same_thing();\n    }\n    if (condition_C &amp;&amp; (condition_D) {\n       do_this_same_thing();\n    }\n    if (condition_E &amp;&amp; condition_F) {\n       do_this_same_thing();\n    }\n</code></pre>\n\n<p>Most of the static analysis tools for examining code will complain if multiple conditional expressions do not use explicit parenthesis dictating expression analysis, instead of relying on operator precedence rules and fewer parenthesis.</p>\n\n<p>Vertical alignment  at the same indent level of open/close braces {}, open close parenthesis (), conditional expressions with parenthesis and operators on the left is an very useful practice, which greatly ENHANCES readability and clarity of the code as opposed to jamming everything that can possibly be jammed onto a single line, sans vertical alignment, spaces or parenthesis</p>\n\n<p>Operator precedence rules are tricky, e.g. &amp;&amp; has higher precedence than ||, but | has precedence than &amp;&amp;</p>\n\n<p>So, ...</p>\n\n<pre><code>    if (expr_A &amp; expr_B || expr_C | expr_D &amp; expr_E || expr_E &amp;&amp; expr_F &amp; expr_G || expr_H {\n    }\n</code></pre>\n\n<p>is a really easy multiple conditional expression for mere humans to read and evaluate improperly.</p>\n\n<pre><code>    if (   (  (expr_A)\n            &amp; (expr_B)\n           )\n        || (  (expr_C)\n            | (  (expr_D)\n               &amp; (expr_E)\n              )\n           )\n        || (   (expr_E)\n            &amp;&amp; (  (expr_F)\n                &amp; (expr_G)\n               )\n           )\n        || (expr_H)\n       )\n    {\n    }\n</code></pre>\n\n<p>There is nothing wrong with horizontal space (linefeeds), vertical alignment, or explicit parenthesis guiding expression evaluation, all of which ENHANCES readability and clarity</p>\n'}]
['https://Stackoverflow.com/questions/6126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384652/']