What is cyclomatic complexity?

13

Regarding the complexity of algorithms, I noticed that there are several quotes about cyclomatic complexity . What is cyclomatic complexity? In what situation is it important to analyze this complexity?

    
asked by anonymous 29.03.2017 / 18:59

2 answers

13

It is a measure of the complexity of an algorithm where the independent paths that the algorithm can take are considered. The more difficult the cyclomatic complexity to follow the code, the more maintenance, testing and full coverage.

Cyclomatic complexity increases whenever there is a branch , but some forms of branch can lead to more difficult paths to follow than others. The more linear, the easier it is to keep track of the code.

An output of the function is still a branch and counts to increase the cyclomatic complexity, so there is no CC 0 function.

So use multiple return or eventually use goto can increase or decrease the cyclomatic complexity depending on how they are used, although it may detract from another aspect.

Large functions tend to have greater cyclomatic complexity. It is very rare to be able to do anything big without branches .

The analysis passes to represent the execution flow through a graph . An example taken from Wikipedia :

ThiscodehasCC3sincethereare2typical(aloopandaconditional)and1exitpoint.

Theaveragedeveloperjustneedstoknowthatheshouldkeepthecomplexitylowbysimplifyingthepossiblepaths.Thisgreatlyeasesyourworkanddecreasestheamountofproblemsthatcanoccur.Moremathematicalquestionsareusefulforcomputerscientistsorengineerswhoneedtoworkwithmoreformaldevelopmentorhighlyoptimizedroutines.

OnepointtoconsideristhatbreakingonefunctionintoseveralcandecreasetheCCofthisfunction,butitdoesnotdecreasetheCCofthealgorithmasawhole.Itmayevenincrease.ProblemsasawholehasalimitofwhatitcantoreduceCC,whatthedevelopercandoistodecreasewhereCCisinexaggeration,unnecessary.Somepeoplemaysaythatatleastitiseasiertotest,thisistruefortheindividualizedtestthathaslittlevalue,youstillneedtotestallsituationsandthishastoconsidertheresultsproducedbytheauxiliaryfunctions.

  

Inwhatsituationisitimportanttoanalyzethiscomplexity?

Inanysituationotherthanatrivialandperhapsdisposablecodeitisgoodtothinkaboutthisandseeifyoucansimplifysomething.

Therearetoolsformeasuringthecyclomaticcomplexityofyourcodeinseverallanguages,someevensuggestrefactoringthatcansimplify.Soyoudonothavetowastetimedoingitmanually.

An example that shows even how she actually does the account .

Original study .

    
29.03.2017 / 20:28
5

Cyclomatic complexity illustrated:

Think about how this would be the graph that @bigown exemplified above. : -)

    
31.03.2017 / 14:13