Skip to content
-
Subscribe to our newsletter & never miss our best posts. Subscribe Now!
  • https://www.facebook.com/
  • https://twitter.com/
  • https://t.me/
  • https://www.instagram.com/
  • https://youtube.com/
https://pctechmag.co.uk/ PC Tech Mag

Tech news, gadget reviews, tips, and digital trends — PC Tech Mag keeps you informed on everything technology.

https://pctechmag.co.uk/ PC Tech Mag

Tech news, gadget reviews, tips, and digital trends — PC Tech Mag keeps you informed on everything technology.

  • Home
  • About us
  • Contact us
  • Tech

About This Site

PC Tech Mag is an online tech magazine with PC hardware and gaming guides, Windows tips, software explainers and gadget coverage.

Recent Posts

  • How to Find Duplicates in Google Sheets: 5 Easy Methods
  • How to Add Speaker Notes in PowerPoint: A Step-by-Step Guide
  • Lighter Linux: The Best Lightweight Linux Distros for Old and Slow PCs
  • Ubuntu vs Mint: Which Linux Distro Should You Choose in 2026?
  • How Do I Send a GIF in a Text Message? A Complete Guide for iPhone and Android

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Find Us

Contact: farmanali5starseo@gmail.com

  • Home
  • About us
  • Contact us
  • Tech
Subscribe
Close

Search

Python code open in a modern code editor on a monitor — best python ides
Software & Apps

Cyclomatic Complexity: What It Is, How to Calculate It and Good Values

By admin
November 26, 2026 9 Min Read
0

Cyclomatic complexity is a number that measures how complicated a piece of code is, based on how many different paths can run through it. A simple function with no branches has a cyclomatic complexity of 1. Every time you add an if, a loop, a case, or a logical and or or, the number goes up by one, because you have added another path that a test must cover. In short, the higher the number, the harder the code is to understand, test, and change safely.

The measure was introduced by Thomas J. McCabe in 1976, and it is still used today in code reviews, in static analysis tools, and in quality gates that stop very complex code from being merged. This guide explains what cyclomatic complexity means in plain English, how to calculate it by hand and with tools, what a good value is, and how to reduce it when it gets too high.

What Is Cyclomatic Complexity?

Think of a function as a maze. At the start there is one way in. Every decision point — an if statement, a while loop, a for loop, a switch case, a catch block — is a fork in the maze, and each fork adds a new route through it. Cyclomatic complexity counts those routes. A function with a complexity of 1 has a single route, so you only need one test to run through all of it. A function with a complexity of 10 has ten independent routes, so you need at least ten tests to cover them all, and a reader has to hold ten possibilities in their head at once.

That is why the number matters even though it is only a rough measure. It does not tell you whether the code is correct, whether it is fast, or whether it is well written. It tells you how much branching is in one place, and branching is where bugs hide. A function with a complexity of 30 is not automatically wrong, but it is a strong signal that the function is doing too many things, that it will be hard to test, and that a change in one branch may break another.

How to Calculate Cyclomatic Complexity

There are three equivalent ways to calculate it, and they should all give the same answer for the same function. The easiest for most developers is to count decision points and add one.

Method 1: Count Decision Points and Add One

Start with 1, then add 1 for each of the following in the function: each if, else if, for, while, do while, case, catch, and each logical operator, and and or, in a condition. A ternary operator also counts as a decision point in most tools, because it is a branch, even though it is written on one line.

def can_borrow(age, has_card):
    if age < 18:
        return False
    if not has_card:
        return False
    return True

This function has two if statements, so its complexity is 1 + 2 = 3. There are three paths through it: too young, no card, and can borrow. That matches the intuition that you need three tests to cover it properly.

Method 2: The Control Flow Graph Formula

McCabe’s original formula is V(G) = E – N + 2P, where E is the number of edges in the control flow graph, N is the number of nodes, and P is the number of connected components, which is 1 for a single function. In practice you will rarely draw the graph by hand, but the formula is useful because it shows that complexity is a property of the shape of the code, not of how many lines it has. A long function with no branches can have a complexity of 1, while a short function full of nested ifs can have a complexity of 20.

Method 3: Count Regions in the Flowchart

If you draw the function as a flowchart, cyclomatic complexity is the number of enclosed regions in the diagram, plus one for the outside region. This is the same number as the other two methods, and it is a good way to check your counting when you are learning. Each time a branch splits the flow and later rejoins it, it creates a new region.

A Worked Example

Consider a function that works out a delivery charge. It has an if for express delivery, an if for a discount code, and a loop that adds a charge for each extra item. That is three decision points, so its complexity is 4. If you then add a check for a rural postcode and a check for a weekend delivery, the complexity rises to 6, and you need at least six tests to cover every combination of those decisions. The code has not become longer in a dramatic way, but it has become noticeably harder to reason about, because the number of combinations is growing.

def delivery_charge(order):
    charge = 5.00
    if order.express:
        charge += 10.00
    if order.discount_code:
        charge *= 0.9
    for item in order.extra_items:
        charge += 2.00
    return charge

Now compare that with a function that does the same work by calling three small helpers, one for express delivery, one for the discount, and one for extra items. Each helper has a complexity of 2, and the main function has a complexity of 1, because it has no branches of its own. The total number of paths has not changed, but each piece is now easy to understand and test on its own. That is the main practical benefit of keeping complexity low in each function.

What Is a Good Cyclomatic Complexity Value?

There is no single perfect number, but the ranges below are the ones most teams use, based on McCabe’s original guidance and on common practice in industry tools.

Complexity Risk What it means
1 to 10 Low Simple, easy to test and maintain
11 to 20 Moderate More complex, but acceptable for most code
21 to 50 High Hard to test, consider refactoring
Over 50 Very high Very hard to test, refactor as a priority

Many teams set a quality gate at 10 or 15, which means a function above that limit will fail a check and must be reviewed before it is merged. That does not mean a function with a complexity of 12 is bad, or that a function with a complexity of 9 is good. It means the team has agreed that above 10, the cost of testing and maintaining the function starts to outweigh the convenience of keeping it in one place. Some code, such as a parser or a state machine, is naturally branchy, and teams often allow a higher limit for those files, or exclude them from the gate, rather than forcing a bad refactor.

Cyclomatic Complexity vs Cognitive Complexity

Cyclomatic complexity counts every branch equally, whether it is a simple if at the top level or a deeply nested if inside three loops. Cognitive complexity, a newer measure used by SonarQube and similar tools, gives extra weight to nesting, because nested code is harder for a person to follow than flat code. A function with five flat if statements has a cyclomatic complexity of 6 and a low cognitive complexity, while a function with five nested if statements has the same cyclomatic complexity but a much higher cognitive complexity.

Use cyclomatic complexity when you need a simple, standard number for test coverage, because it tells you the minimum number of tests you need. Use cognitive complexity when you are judging how hard code is for a person to read. Most teams benefit from looking at both, and from treating a high score on either one as a prompt to look at the code, not as a verdict on its own.

How to Measure Cyclomatic Complexity

You should not calculate complexity by hand for a whole project. Use a tool, and let it report the numbers for every function, so you can see which ones are the worst and track whether they are getting better or worse over time.

Tools for Python

For Python, radon is a popular free tool: run radon cc on a file, and it lists the complexity of each function. Xenon can be used as a quality gate, failing a build if a function is above a limit you set. Pylint and flake8 with plugins can also report complexity, and many editors show it as you type. If you are writing Python, our guide on how to append in Python with list.append() shows the kind of small, clear functions that tend to have low complexity, and the best Python IDEs for beginners and pros includes editors that integrate these checks, so you can see complexity warnings while you code instead of after you have finished.

Tools for Other Languages

For JavaScript and TypeScript, ESLint has a complexity rule that warns when a function is above a limit. For Java and C#, SonarQube, PMD, and built-in IDE inspections report cyclomatic and cognitive complexity. For most languages, the same idea applies: add the tool to your project, set a limit that fits your team, and fix the worst offenders first, rather than trying to make every function perfect at once.

How to Reduce Cyclomatic Complexity

Reducing complexity is not about gaming the number. It is about making the code easier to understand, and the number should fall as a side effect. The techniques below are the ones that work most often.

1. Extract a Helper Function

Take a block of code that handles one decision and move it into its own function with a clear name. The main function becomes shorter and simpler, and the helper can be tested on its own. This is the single most useful technique, and it works for almost every complex function.

2. Replace Nested Ifs With Early Returns

Instead of nesting ifs inside ifs, check the failure cases first and return early. A function that starts with three guard clauses and then does its main work in a straight line is much easier to follow than a function that nests the main work three levels deep.

3. Use a Lookup Table Instead of a Long If-Else Chain

If a function chooses between many values with a long chain of if and else if, replace the chain with a dictionary or a map from the input to the result. The lookup has a complexity of 1, and adding a new case is a one-line change instead of a new branch.

4. Replace a Switch With Polymorphism

In object-oriented code, a long switch on a type is often a sign that the behaviour belongs in the classes themselves. Moving the behaviour into a method on each class removes the switch and the branches that went with it.

5. Simplify Conditions

Combine related conditions, give a complex condition a name by storing it in a well-named variable, and avoid negations where you can. A condition that reads as a sentence is easier to test than a condition that is a puzzle.

Do not refactor just to lower a number. If a function is complex because the problem itself is complex, and the code is clear and well tested, leave it alone. Refactor when the complexity is making the code hard to change, hard to test, or a frequent source of bugs.

Frequently Asked Questions

What is cyclomatic complexity in simple terms?

Cyclomatic complexity is a number that counts how many different paths can run through a piece of code. A simple function with no branches has a complexity of 1, and each if, loop, or logical operator adds one more path, and one more to the number.

What is a good cyclomatic complexity?

A complexity of 1 to 10 is generally considered good and low risk. Values of 11 to 20 are moderate and usually acceptable, values of 21 to 50 are high and should be reviewed, and values over 50 are very high and should be refactored as a priority.

How do you calculate cyclomatic complexity?

Start with 1 and add 1 for each decision point in the function, including each if, else if, for, while, case, catch, and each and or or in a condition. That total is the cyclomatic complexity, and it is also the minimum number of tests needed to cover every path.

Can cyclomatic complexity be too low?

No, in practice a low number is not a problem. A complexity of 1 means the code has a single path, which is easy to test. Very low complexity across a whole project can mean the code is split into many tiny functions, but that is usually a good trade-off if the functions are well named.

Does cyclomatic complexity measure code quality?

It measures one aspect of code quality: how much branching is in a function, and therefore how hard it is to test and maintain. It does not measure correctness, performance, readability, or design, so use it alongside code review, tests, and other measures, not as a single score for quality.

Cyclomatic complexity is a simple, useful number: start at 1, add 1 for every branch, and you have the minimum number of tests a function needs. Keep most functions at 10 or below, use a tool to find the outliers, and split the worst functions into smaller helpers with clear names. Your code will be easier to test, easier to change, and easier for the next person to understand.

Author

admin

Follow Me
Other Articles
Illustration of a Windows laptop screen with open windows being cleaned up, representing removing old mapped drives in Windows
Previous

Windows 10 ESU: What It Is, How Much It Costs and How to Enrol

Illustration of a computer monitor with circular arrows showing screen rotation
Next

Concept Map Generator: What It Is and the Best Free Tools in 2026

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

About This Site

PC Tech Mag is an online tech magazine with PC hardware and gaming guides, Windows tips, software explainers and gadget coverage.

Search

Recent Posts

  • How to Find Duplicates in Google Sheets: 5 Easy Methods
  • How to Add Speaker Notes in PowerPoint: A Step-by-Step Guide
  • Lighter Linux: The Best Lightweight Linux Distros for Old and Slow PCs
  • Ubuntu vs Mint: Which Linux Distro Should You Choose in 2026?
  • How Do I Send a GIF in a Text Message? A Complete Guide for iPhone and Android

Find Us

Contact: farmanali5starseo@gmail.com

About This Site

PC Tech Mag is an online tech magazine with PC hardware and gaming guides, Windows tips, software explainers and gadget coverage.

Recent Posts

  • How to Find Duplicates in Google Sheets: 5 Easy Methods
  • How to Add Speaker Notes in PowerPoint: A Step-by-Step Guide
  • Lighter Linux: The Best Lightweight Linux Distros for Old and Slow PCs
  • Ubuntu vs Mint: Which Linux Distro Should You Choose in 2026?
  • How Do I Send a GIF in a Text Message? A Complete Guide for iPhone and Android

Archives

  • December 2026 (15)
  • November 2026 (192)
  • October 2026 (85)

Find Us

Contact: farmanali5starseo@gmail.com

Copyright 2026 — PC Tech Mag. All rights reserved. Blogsy WordPress Theme