Cyclomatic Complexity
Cyclomatic Complexity is the number of independent paths through code and there are many websites that do a better job of explaining it than I can, but...
The formula is;
M = E − N + 2P
where
E = the number of edges of the graph.
N = the number of nodes of the graph.
P = the number of connected components.
(For 1 graph, P=1, if there are more separated clusters, P is the number of clusters of separate graphs)
This is applicable to Fig.1
If however the graph is as per Fig.2, the following should be used;
M = E − N + P
Fig.2 shows a graph where the exit point is corrected back to the entry point.
Fig.1 & 2 are from https://en.wikipedia.org/wiki/Cyclomatic_complexity
Another way, is to count each decision block and add 1 for the entry point of the code.
Fig.1 - M = E − N + 2P
Fig.2 - M = E − N + P
A final point of note is that even if you can visualise more independent paths through the code, this may not be correct, as an independent path is one where each edge has been touched at least once.
So in the example in Fig.3 we may count f paths as follows:
1) A > B > D > E > G
2) A > B > D > F > G
3) A > C > D > E > G
4) A > C > > > F > G
This would be incorrect for Cyclomatic Complexity as after 2 above, we can have only either of 3 or 4 cause then every edge will have been touched at least once, so the Cyclomatic Complexity for Fig.3 would be in fact 3, as can be calculated as follows:
M = E − N + 2P
M = (8-7) + 2x1
M=1+2
M=3
The other method, is:
A has 1 decision point, as has D, giving 2 + 1 (for the start point), giving us 3
Fig.3
No comments:
Post a Comment
Note: only a member of this blog may post a comment.