Misconception on IF ELSE condition

This advice came from a software metric which called Cyclomatic complexity or Conditional complexity.

Definition:

The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code. For instance, if the source code contained no decision points such as IF statements or FOR loops, the complexity would be 1, since there is only a single path through the code. If the code had a single IF statement containing a single condition there would be two paths through the code, one path where the IF statement is evaluated as TRUE and one path where the IF statement is evaluated as FALSE.

So

Do they say that I should not use if/else at all (!) or to avoid if/else nesting?

No you shouldn’t avoid if/else at all! but you should be careful about Cyclomatic complexity of your code. More code complexity tends to have more defects. According to this the right limit would be 11. A tool called Code Complete categorize the score like that Ref.:

  • 0-5– the routine is probably fine
  • 6-10– start to think about ways to simplify the routine
  • 10+– break part of the routine into a second routine and call it from the first routine

How to calculate Cyclomatic complexity “basically”:

From example here: consider the following pseudo code :

please note that this metric is concerned about number of decision in your program/code so from the code above we could say that we have 3 decisions ( 3 values of A)

let’s calculate it formally so consider the following control flow of the code:

The complexity M is then defined* as:Ref

where

E = the number of edges of the graph

N = the number of nodes of the graph

P = the number of connected components (exit nodes).

by applying the formula E(flow lines) = 8 , N (nodes)= 7 , P (exit nodes) =1 then M = 8-7 + (2*1) = 3

*there is also another definition stated but it is close :M = E − N + P check the reference for theory.

Please note that many of static code analysis tools could calculate the Cyclomatic complexity of your code.

 

For more detail on Cyclomatic complexity or Conditional complexity please visit to wiki page.

https://en.wikipedia.org/wiki/Cyclomatic_complexity

 

Basant is a full stack developer, software engineer and freelancer with broad and deep experience developing web applications. He has been working with web based tech companies in India for over 10 years, helping to build technology-based businesses from the ground up. He excels at programming back-end and front-end services in a variety of languages, and holds a Master’s degree in Computer Application.