100

If you want to some code to execute based on two or more conditions which is the best way to format that if statement ?

first example:-

if(ConditionOne && ConditionTwo && ConditionThree)
{
   Code to execute
}

Second example:-

if(ConditionOne)
{
   if(ConditionTwo )
   {
     if(ConditionThree)
     {
       Code to execute
     }
   }
}

which is easiest to understand and read bearing in mind that each condition may be a long function name or something.

1
  • Pity that nobody on this page mentions the substring "fast" or "performance". That's what I came here to learn. May 19, 2019 at 10:28

10 Answers 10

145

I prefer Option A

bool a, b, c;

if( a && b && c )
{
   //This is neat & readable
}

If you do have particularly long variables/method conditions you can just line break them

if( VeryLongConditionMethod(a) &&
    VeryLongConditionMethod(b) &&
    VeryLongConditionMethod(c))
{
   //This is still readable
}

If they're even more complicated, then I'd consider doing the condition methods separately outside the if statement

bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);
bool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);
bool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);

if( aa && bb && cc)
{
   //This is again neat & readable
   //although you probably need to sanity check your method names ;)
}

IMHO The only reason for option 'B' would be if you have separate else functions to run for each condition.

e.g.

if( a )
{
    if( b )
    {
    }
    else
    {
        //Do Something Else B
    }
}
else
{
   //Do Something Else A
}
3
  • I like it. Although I'm not a huge fan of the method idea, unless the methods already exist and return a boolean value. Nov 3, 2008 at 17:26
  • 2
    Aren't you evaluating everything without a reason in the second example?
    – Odys
    Dec 24, 2016 at 16:19
  • I would use the '&&' before the condition. It's hard to have conditions with the same character length as in the example.
    – anegru
    Aug 4, 2020 at 11:03
31

Other answers explain why the first option is normally the best. But if you have multiple conditions, consider creating a separate function (or property) doing the condition checks in option 1. This makes the code much easier to read, at least when you use good method names.

if(MyChecksAreOk()) { Code to execute }

...

private bool MyChecksAreOk()
{ 
    return ConditionOne && ConditionTwo && ConditionThree;
}

It the conditions only rely on local scope variables, you could make the new function static and pass in everything you need. If there is a mix, pass in the local stuff.

5
  • 2
    I found this to be the most effective and easier to add conditions later on
    – pbojinov
    Nov 25, 2011 at 9:23
  • +1 at first I raised an eyebrow but this really is the best answer imho. having that boolean isOkToDoWhatever as a property makes a lot of sense.
    – grinch
    Nov 8, 2012 at 1:30
  • 1
    But this just moves the same complex condition elsewhere where it also needs to be readable so we're back to square one with this. It's not just about ifstatement readability but rather condition readability. May 17, 2016 at 8:15
  • @RobertKoritnik I understand what you're saying, but I don't think we're back to square one because we have reduced the complexity the reader needs to consider in one go. She may look at the conditions, OR she may look at the code using the conditions where the conditions have a (hopefully) nice name. At least I often finds this easier to grok, but then again sometimes it's nice to have all the details in one place. As always, it depends.
    – Torbjørn
    May 26, 2016 at 23:03
  • Great point utilizing good method names and refactoring of logic.
    – JB Lovell
    Jan 27, 2017 at 2:52
16
if (   ( single conditional expression A )
    && ( single conditional expression B )
    && ( single conditional expression C )
   )
{
   opAllABC();
}
else
{
   opNoneABC();
}

Formatting a multiple conditional expressions in an if-else statement this way:

  1. allows for enhanced readability:
    a. all binary logical operations {&&, ||} in the expression shown first
    b. both conditional operands of each binary operation are obvious because they align vertically
    c. nested logical expressions operations are made obvious using indentation, just like nesting statements inside clause
  2. requires explicit parenthesis (not rely on operator precedence rules)
    a. this avoids a common static analysis errors
  3. allows for easier debugging
    a. disable individual single conditional tests with just a //
    b. set a break point just before or after any individual test
    c. e.g. ...
// disable any single conditional test with just a pre-pended '//'
// set a break point before any individual test
// syntax '(1 &&' and '(0 ||' usually never creates any real code
if (   1
    && ( single conditional expression A )
    && ( single conditional expression B )
    && (   0
        || ( single conditional expression C )
        || ( single conditional expression D )
       )
   )
{
   ... ;
}

else
{
   ... ;
}
1
  • 3
    This is my method. The only problem I have is I have yet to find a code beautifier which offers this as an option
    – Speed8ump
    Jul 25, 2019 at 15:04
11

The first example is more "easy to read".

Actually, in my opinion you should only use the second one whenever you have to add some "else logic", but for a simple Conditional, use the first flavor. If you are worried about the long of the condition you always can use the next syntax:

if(ConditionOneThatIsTooLongAndProbablyWillUseAlmostOneLine
                 && ConditionTwoThatIsLongAsWell
                 && ConditionThreeThatAlsoIsLong) { 
     //Code to execute 
}

Good Luck!

10

The question was asked and has, so far, been answered as though the decision should be made purely on "syntactic" grounds.

I would say that the right answer of how you lay-out a number of conditions within an if, ought to depend on "semantics" too. So conditions should be broken up and grouped according to what things go together "conceptually".

If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line

Eg.

if user.hasPermission(Admin()) {
   if (x >= 0) && (x < 100) {
      // do something
   }
}
0
4

The second one is a classic example of the Arrow Anti-pattern So I'd avoid it...

If your conditions are too long extract them into methods/properties.

3

The first one is easier, because, if you read it left to right you get: "If something AND somethingelse AND somethingelse THEN" , which is an easy to understand sentence. The second example reads "If something THEN if somethingelse THEN if something else THEN", which is clumsy.

Also, consider if you wanted to use some ORs in your clause - how would you do that in the second style?

0

In Perl you could do this:

{
  ( VeryLongCondition_1 ) or last;
  ( VeryLongCondition_2 ) or last;
  ( VeryLongCondition_3 ) or last;
  ( VeryLongCondition_4 ) or last;
  ( VeryLongCondition_5 ) or last;
  ( VeryLongCondition_6 ) or last;

  # Guarded code goes here
}

If any of the conditions fail it will just continue on, after the block. If you are defining any variables that you want to keep around after the block, you will need to define them before the block.

1
  • 1
    That looks Perlish - in the "it does WHAT?" sense ;) But it's actually readable, once you get used to it. Aug 20, 2010 at 13:35
-3

I've been facing this dilemma for a long time and I still can't find a proper solution. In my opinion only good way is to first try to get rid of conditions before so you're not suddenly comparing 5 of them.

If there's no alternative then like others have suggested - break it down into separete ones and shorten the names or group them and e.g. if all must be true then use something like "if no false in array of x then run".

If all fails @Eoin Campbell gave pretty good ideas.

1
  • This isn't adding anything new to the already existing answers.
    – jerney
    Aug 17, 2018 at 16:44
-4

When condition is really complex I use the following style (PHP real life example):

if( $format_bool &&
    (
        ( isset( $column_info['native_type'] )
            && stripos( $column_info['native_type'], 'bool' ) !== false
        )
        || ( isset( $column_info['driver:decl_type'] )
            && stripos( $column_info['driver:decl_type'], 'bool' ) !== false
        )
        || ( isset( $column_info['pdo_type'] )
            && $column_info['pdo_type'] == PDO::PARAM_BOOL
        )
    )
)

I believe it's more nice and readable than nesting multiple levels of if(). And in some cases like this you simply can't break complex condition into pieces because otherwise you would have to repeat the same statements in if() {...} block many times.

I also believe that adding some "air" into code is always a good idea. It improves readability greatly.