To truly grasp CYC, let’s walk through a simple example. This metric measures the number of independent paths through your code, essentially how many different routes your program can take during execution. Lower scores are a sign of clean, easy-to-understand code that’s simple to test and maintain. Higher scores? They’re a red flag that your code might be more tangled than necessary, making future updates and testing trickier.
Take a look at this basic function. It checks if a number is positive and, if so, prints a message. Because there’s only one decision point here, this function has a CYC score of 1. That means it’s straightforward, easy to maintain, and unlikely to cause headaches down the line.
This function is a great example of simplicity and reliability, with just one clear path through the code, no branches, and no extra conditions.
def is_positive(num):
if num > 0:
print("Positive number")Then, let’s look at a somewhat more complex function containing several conditions. As can be seen, this function has new decision points when compared to the previous example.
Each of these decision points increases the code complexity and raises the CYC score. Firstly, the if statement introduces one decision point, and the elif statement then adds another decision point, which increases the overall complexity. The else clause creates a third branch, making the function even more layered:
def check_number(num):
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")This means that the code has four execution paths and a CYC score of 4. This score predicts that the code will not be much more complicated than the first example to maintain, and should still be easy to manage. It is still within the ideal range.
When a CYC score is anywhere above 10, the code becomes harder to understand, test, and change. As a rule, developers aim to keep their code complexity as low as possible, as complicated code makes it much more challenging for future developers or teams to update.
By tracking CYC, developers can maintain clean, well-structured, reliable and scalable code.