Nested and combined conditions

Which of these two examples will work best:

Example 1:

if($condition_1)
{
 if($condition_2)
 {
  // do something
 }
}

Example 2:

if($condition_1 and $condition_2)
{
 // do something
}
+3
source share
6 answers

The difference, if any, will be negligible. You don’t have to worry about the second evaluating both conditions due to the short circuit rating.

IMO the second form makes the code more readable. I hate to see millions of indents.

+6
source

-. , - , , , . . , , : "if" "else", , "ifs" .

+6

, . .

+2

Cyclomatic Complexity. if-

Lines of Code (LOC):                                  6
  Cyclomatic Complexity / Lines of Code:           0.40
Comment Lines of Code (CLOC):                         1
Non-Comment Lines of Code (NCLOC):                    5

Lines of Code (LOC):                                  9
  Cyclomatic Complexity / Lines of Code:           0.25
Comment Lines of Code (CLOC):                         1
Non-Comment Lines of Code (NCLOC):                    8

, , . CC 0,67. , , , .

, , .

: , , LOC: <?php ,

+2

:

, .

So, if you write cond1 and cond2, it stops if it cond1gets false. So this is not even a difference in speed.

+1
source

If this is just one block, skip to the later option, as it requires less indentation, shorter, and possibly more readable.

However, note that from now on you will use the first option, because you add elses. They are not necessarily the same:

if ($condition_1) {
    if ($condition_2) {
        // do something
    }
    else {
        //do something else
    }
}

if ($condition_1) {
    if ($condition_2) {
        // do something
    }
}
else {
    //do something else
}
0
source

Source: https://habr.com/ru/post/1757472/


All Articles