Code Fragment
function isAdult(age) {
if (age >= 18) {
console.log("It is an adult");
return true;
} else if (age < 0) {
console.error(`The age "${age}" is incorrect`);
}
return false;
}
Flow Graph
Calculate V(G)
Cyclomatic Complexity (V(G)) is calculated using the formula:
V(G) = A - N + 2
Where:
-
A is the number of edges
-
N is the number of nodes
Alternatively, we can calculate V(G) using the number of predicates (decision nodes):
V(G) = P + 1
Where:
-
P is the number of decision nodes in the flow.
In our case, we have:
-
5 nodes: Start, Decision 1 (
age >= 18), Decision 2 (age < 0), logging blocks, and End. -
2 predicates:
age >= 18andage < 0.
Thus, V(G) = 2 + 1 = 3.
Therefore, the cyclomatic complexity of the function is 3.
Determine Independent Execution Paths
There are 3 independent execution paths:
-
Path 1: age >= 18 (true) →
It is an adult→return true→ End. -
Path 2: age < 0 (true) →
Error: The age is incorrect→ End. -
Path 3: age >= 18 (false) → age < 0 (false) →
return false→ End.
Input Values for Each Independent Path
To test each independent path, we use the following input values:
-
Path 1: Test with
age = 20(greater than or equal to 18). -
Path 2: Test with
age = -5(less than 0). -
Path 3: Test with
age = 15(between 0 and 18).