# How to Reduce Cyclomatic Complexity: A Complete Guide | LinearB Blog

> How to reduce cyclomatic complexity? In this post, you’ll learn not only that, but also what is this metric and why you should reduce it.

_This is a markdown rendering of a live HTML page on linearb.io, generated for AI/LLM consumption — it is not a markdown-only site. To get the full HTML page instead, request this URL with an explicit `Accept: text/html` header (no wildcard, no markdown preference)._


```json
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [
    {
      "@type": "ListItem",
      "position": 1,
      "name": "Home",
      "item": "https://linearb.io/"
    },
    {
      "@type": "ListItem",
      "position": 2,
      "name": "Blog",
      "item": "https://linearb.io/blog"
    },
    {
      "@type": "ListItem",
      "position": 3,
      "name": "How to Reduce Cyclomatic Complexity: A Complete Guide",
      "item": "https://linearb.io/blog/reduce-cyclomatic-complexity"
    }
  ]
}
```

[Home](https://linearb.io/)

/

[Blog](https://linearb.io/blog)

/

How to Reduce Cyclomatic Complexity: A Complete Guide

# How to Reduce Cyclomatic Complexity: A Complete Guide

![Photo of Carlos Schults](https://assets.linearb.io/image/upload/c_limit,w_2560/f_auto/q_auto/v1/logo-mark-lg?_a=BAVMn6ID0)

By [Carlos Schults](https://linearb.io/blog/reduce-cyclomatic-complexity#carlos-schults)

|

February 23, 2021

![luca_bravo_XJX_Wbf_So2f0_unsplash_scaled_abbd6e7e6e](https://assets.linearb.io/image/upload/c_limit,w_2560/f_auto/q_auto/v1/luca_bravo_XJX_Wbf_So2f0_unsplash_scaled_abbd6e7e6e?_a=BAVMn6ID0)

Software engineers worth their salt are always searching for ways to improve their code quality. Fortunately for them, there’s a reliable way to evaluate the health of a codebase and project, and that’s through the use of [metrics](https://linearb.io/metrics-modern-dev-leaders). Today’s post is all about a specific metric. You’ll learn how to reduce cyclomatic complexity and, more importantly, why you would want to do it.

We’ll start by [defining cyclomatic complexity](https://linearb.io/blog/cyclomatic-complexity). After that, you’ll learn why having cyclomatic complexity too high is a problem and why you would need to reduce it.

After the “what” and “why,” we’ll finally get to the “how.” We’ll show you tactics you can adopt to reduce the cyclomatic complexity of your code. Let’s get to it.

![how to reduce cyclomatic complexity](https://assets.linearb.io/uploads/LinearB-2.png)

## What is Cyclomatic Complexity?

Cyclomatic complexity refers to the number of possible execution paths inside a given piece of code—for instance, a function. The more decision structures you use, the more possible branches there are for your code.

Cyclomatic complexity is especially important when it comes to testing. By calculating the cyclomatic complexity of a function you know the minimum number of test cases you’ll need to achieve full branch coverage of that function. So, we can say that cyclomatic complexity can be a predictor of how hard it is to test a given piece of code.

[![Confused Thinking GIF Find & Share on GIPHY](https://media2.giphy.com/media/WRQBXSCnEFJIuxktnw/giphy.gif)](https://giphy.com/gifs/math-lady-meme-WRQBXSCnEFJIuxktnw)

Confused? Understanding cyclomatic complexity doesn’t have to be complex.

Cyclomatic complexity is the minimum number of test cases needed to achieve full [branch coverage](https://linearb.io/blog/what-is-branch-coverage). So cyclomatic complexity can predict how hard it is to test a given piece of code.

## A Dead Simple Cyclomatic Complexity Example

Consider the following function written in pseudocode:

void sayHello(name) {

print(“Hello, ${name}!”);

}

Since it has a single statement, it’s easy to see its cyclomatic complexity is 1.

[![Deadpool Hello GIF by moodman Find & Share on GIPHY](https://media0.giphy.com/media/xUyrMCdgrOL3ntbTvK/giphy.gif)](https://giphy.com/gifs/reaction-mood-xUyrMCdgrOL3ntbTvK)

Now, let’s change things a little bit:

void sayHello(name, sayGoodbye = false) {

print(“Hello, ${name}!”);

if (sayGoodbye) {

print(“Goodbye, ${name}!”);

}

}

[![Tom Hiddleston Goodbye GIF by Marvel Studios Find & Share on GIPHY](https://media0.giphy.com/media/UYzSmRaDu5eVpbvZqw/giphy.gif)](https://giphy.com/gifs/marvelstudios-marvel-tom-hiddleston-loki-UYzSmRaDu5eVpbvZqw)

The second version of the function has a branch in it. The caller to the function might pass **true** as the value for the **sayGoodbye** parameter, even though the default value is **false**. If that does happen, the function will print a goodbye message after saying hello. On the other hand, if the caller doesn’t supply a value for the parameter or chooses **false**, the goodbye message won’t be displayed.

So, the function has two possible execution branches, which is the same as saying that it has a cyclomatic complexity value of 2.

## Why Is Cyclomatic Complexity Bad?

Cyclomatic complexity isn’t intrinsically bad. For instance, you can have a piece of code with a somewhat high cyclomatic complex value that’s super easy to read and understand.

However, generally speaking, we can say that having a too high cyclomatic complexity is either a symptom of problems with the codebase or a potential cause of future problems. Let’s cover some of the reasons why you’d want to reduce it in more detail.

### Cyclomatic Complexity Might Contribute to Cognitive Complexity

Cognitive complexity refers to how difficult it is to understand a given piece of code. Though that’s not always the case, cyclomatic complexity can be one of the factors driving up cognitive complexity. The higher the [cognitive complexity](https://linearb.io/blog/cognitive-complexity-in-software) of a piece of code, the harder it is to navigate and maintain.

### Cyclomatic Complexity Makes Code Harder to Test

As we’ve already mentioned, higher values of cyclomatic complexity result in the need for a higher number of test cases to comprehensively test a block of code—e.g., a function. So, if you want to make your life easier when writing tests, you probably want to reduce the cyclomatic complexity of your code.

### Cyclomatic Complexity Contributes to Higher Risk of Defects

You’re likelier to introduce defects to an area of the codebase that you change a lot than to one you rarely touch. In addition, the more complex a given piece of code is, the more likely you are to misunderstand it and introduce a defect to it.

So, complex code that suffers a lot of [churn](https://linearb.io/blog/what-is-code-churn)—frequent changes by the team—represents more risk of defects. By reducing the cyclomatic complexity—and, ideally, the code churn as well—you’ll be mitigating those risks.

## How to Reduce Cyclomatic Complexity: 6 Practical Ways

We’ll now go over a few practical tips you can use to ensure the cyclomatic complexity of your code is as low as possible.

## 1\. Prefer Smaller Functions

#### What to Do?

All else being equal, smaller functions are easier to read and understand. They’re also less likely to contain bugs by virtue of their length.

If you don’t have too many lines of code, you don’t have lots of opportunities for buggy code. The same reasoning applies for cyclomatic complexity. You’re less likely to have complex code if you have less code period. So, the advice here is to prefer smaller functions.

#### How to Do It?

For each function, identify their core responsibility. Extract what’s left to their own functions and modules. Doing that also makes it easier to reuse code, which is a point we’ll revisit soon.

## 2\. Avoid Flag Arguments in Functions

#### What to Do?

Flag arguments are boolean parameters you add to a function. People usually use them when they need to change how a function works while at the same time preserving the old behavior.

#### How to Do It?

What to use instead of flag parameters? In a nutshell, you can use strategies that accomplish the same result without incurring high complexity. For instance, you could create a new function, maintaining the old one as it is and extracting the common parts into its own private function.

If the flag parameter is being used to enhance or improve the behavior of the original function somehow, you might want to leverage the [decorator pattern](https://en.wikipedia.org/wiki/Decorator%5Fpattern) to reach the same end.

## 3\. Reduce the Number of Decision Structures

#### What to Do?

You might consider this one a no-brainer. If the decision structures—especially **if-else** and switch case—are what cause more branches in the code, it stands to reason that you should reduce them if you want to keep cyclomatic complexity at bay.

#### How to Do It?

Some of the tactics we’ve just seen can contribute to reducing the number of **if** statements in your code. For instance, instead of using flag arguments and then using an **if** statement to check, you can use the decorator pattern.

Instead of using a switch case to go over many possibilities and decide which one the code will execute, you can leverage the [strategy pattern](https://en.wikipedia.org/wiki/Strategy%5Fpattern). Sure, at some point in the code, you’ll still need a switch case. After all, _someone_ has to decide which actual implementation to use. However, that point becomes the only point in the code that needs that decision structure.

## 4\. Get Rid of Duplicated Code

#### What to Do?

Sometimes, you have functions/methods that do almost the same thing. Keeping both increases the total cyclomatic complexity of your class or module. If you can limit your [duplicates](https://linearb.io/blog/code-duplication), you can limit complexity.

#### How to Do It?

Remove duplicated code by:

* extracting the common bits of code to their own dedicated methods/functions.
* leveraging design patterns—such as [template pattern](https://en.wikipedia.org/wiki/Template%5Fmethod%5Fpattern)—that encourage code reuse.
* extracting generic utility functions into packages—gems, npm modules, NuGet packages, etc.—that can be reused through the whole organization.

## 5\. Remove Obsolete Code

#### What to Do?

There are many reasons why it’s a good idea to remove obsolete—i.e., dead—code from your application. For our context, it suffices to say that that’s a “free” way to bring code coverage up and cyclomatic complexity down.

#### How to Do It?

Just use a tool that lets you [identify dead code](https://linearb.io/blog/dead-code)—even your IDE might be able to do it—and then delete it mercilessly.

## 6\. Don’t Reinvent the Wheel

#### What to Do?

Let the developer who never wrote a function—or even a couple of them—to perform date formatting cast the first stone! It’s almost like a rite of passage.

Writing code that simply duplicates functionality that your language’s standard library or your framework already provides is a sure way to increase complexity unnecessarily. If [code is a liability](https://wiki.c2.com/?SoftwareAsLiability), you want to write only the strictly necessary amount of it.

#### How to Do It?

Implement a sound code review strategy that’s able to identify and get rid of such wheel reinventions.

## Reduce Code Complexity, Increase Code Clarity

Cyclomatic complexity is one of the most valuable metrics in software engineering. It has important implications for software quality and maintainability, not to mention testing.

[High cyclomatic complexity might be both a signal of existing problems and a predictor of future ones. ](https://linearb.io/blog/what-is-code-complexity)So, keeping the value of this metric under control is certainly something you want to do if you want to achieve a healthy codebase. Keeping it under control is exactly what you’ve learned with our post.

Before parting ways, a final caveat. Keep in mind that no metric is a panacea when used in isolation.

Often, what you’d really want to do is to track and improve a [group of metrics](https://linearb.io/5-key-metrics-fix-your-software-teams-quality) that, together, can give you the big picture view of the health of your team and project. The best way to do that? [Get a demo of LinearB.](https://linearb.io/get-started)

[](https://linearb.io/code-quality)LinearB is here to help you spot where there might be problems in your process. If you’d like to learn more and improve your own code quality, check out [our five-step recipe for improvement](https://linearb.io/code-quality).

## Improve developer productivity with LinearB

Find us on

[](https://www.linkedin.com/company/linearb)
[](https://devinterrupted.substack.com/)

## Your next read

[![Cover image for Your software factory needs a context layer](https://assets.linearb.io/image/upload/c_limit,w_2560/f_auto/q_auto/v1/unnamed_4_b35455ae7a?_a=BAVMn6ID0)](https://linearb.io/blog/software-factory-2026-ai-benchmarks-code-review-roi)

Eng. Metrics

[Your software factory needs a context layer](https://linearb.io/blog/software-factory-2026-ai-benchmarks-code-review-roi)

Data from 2.7 million pull requests across 253 engineering organizations shows a widening gap between developers using AI deeply and everyone else. An adoption...

[![Cover image for AI agents are killing the pull request and reinventing CI/CD](https://assets.linearb.io/image/upload/c_limit,w_2560/f_auto/q_auto/v1/Blog_Post_Name_2400x1256_5_496cdfde2d?_a=BAVMn6ID0)](https://linearb.io/blog/circleci-rob-zuber-ai-agents-pull-request-cicd-sdlc)

Eng. Metrics

[AI agents are killing the pull request and reinventing CI/CD](https://linearb.io/blog/circleci-rob-zuber-ai-agents-pull-request-cicd-sdlc)

CircleCI CTO Rob Zuber explains why AI adoption is killing the pull request and forcing engineering teams to completely reimagine the software development...

[![Cover image for AI ROI comes from measuring engineering outcomes on day one](https://assets.linearb.io/image/upload/c_limit,w_2560/f_auto/q_auto/v1/Blog_AI_ROI_comes_from_measuring_engineering_software_security_2400x1256_2c5eae0862?_a=BAVMn6ID0)](https://linearb.io/blog/kraken-nik-sudan-measure-ai-roi-engineering-outcomes)

Eng. Metrics

[AI ROI comes from measuring engineering outcomes on day one](https://linearb.io/blog/kraken-nik-sudan-measure-ai-roi-engineering-outcomes)

Kraken Engineering Operations Lead Nik Sudan details how to establish day-one data infrastructure to accurately measure AI ROI. Discover why raw token adoption...

## Structured data

_Machine-readable metadata (JSON-LD) embedded in the page for search/AI context — not content rendered on the page itself._

```json
{
  "@context": "https://schema.org",
  "@type": "Organization",
  "name": "LinearB",
  "url": "https://linearb.io/",
  "logo": "https://assets.linearb.io/image/upload/v1715628027/logo-mark-lg.svg",
  "description": "LinearB is the engineering productivity platform that helps engineering leaders prove AI is improving throughput without sacrificing delivery confidence, flow efficiency, or developer experience.",
  "sameAs": [
    "https://www.linkedin.com/company/linearb"
  ],
  "award": [
    {
      "@type": "Award",
      "name": "LinearB is a Leader in the 2026 Gartner® Magic Quadrant™ for Developer Productivity Insight Platforms",
      "dateAwarded": "2026",
      "awardedBy": {
        "@type": "Organization",
        "name": "Gartner®"
      }
    },
    {
      "@type": "Award",
      "name": "Great Place to Work Certification",
      "dateAwarded": "2025-2027",
      "awardedBy": {
        "@type": "Organization",
        "name": "Great Place to Work"
      }
    },
    {
      "@type": "Award",
      "name": "America's Best Startup Employers 2025",
      "dateAwarded": "2025",
      "awardedBy": {
        "@type": "Organization",
        "name": "Forbes Magazine"
      }
    }
  ],
  "hasCertification": [
    {
      "@type": "Certification",
      "name": "SOC 1 Type 2"
    },
    {
      "@type": "Certification",
      "name": "SOC 2 Type 2"
    },
    {
      "@type": "Certification",
      "name": "GDPR Compliance certification"
    },
    {
      "@type": "Certification",
      "name": "ISO 27001"
    }
  ]
}
```

```json
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "How to Reduce Cyclomatic Complexity: A Complete Guide",
  "url": "https://linearb.io/blog/reduce-cyclomatic-complexity",
  "author": {
    "@type": "Person",
    "name": "Carlos Schults"
  },
  "datePublished": "2021-02-23T18:12:00.000Z",
  "dateModified": "2021-02-23T18:12:00.000Z",
  "image": "https://assets.linearb.io/image/upload/v1720000000/luca_bravo_XJX_Wbf_So2f0_unsplash_scaled_abbd6e7e6e.jpg",
  "publisher": {
    "@type": "Organization",
    "name": "LinearB",
    "logo": "https://assets.linearb.io/image/upload/v1777485755/linearb-logo-2026.png"
  },
  "description": "How to reduce cyclomatic complexity? In this post, you’ll learn not only that, but also what is this metric and why you should reduce it.\n"
}
```

## More on linearb.io

### Top navigation

- [Book a Demo](https://linearb.io/book-a-demo)
- [AI Code Reviews — Catch security risks, bugs, and spec mismatches](https://linearb.io/platform/ai-code-reviews)
- [AI & Productivity Insights — See how AI tools affect cycle time and delivery speed](https://linearb.io/platform/ai-developer-productivity-insights)
- [Measure AI Impact — Track AI adoption and tie it to delivery outcomes](https://linearb.io/use-case/measure-ai-impact)
- [MCP Server — Chat with your data to spot patterns and boost output](https://linearb.io/platform/mcp-server)
- [Resource Allocation — Cost initiatives and shape your investment strategy](https://linearb.io/platform/resource-allocation)
- [Cost Capitalization — Capitalize engineering costs with audit-ready reports](https://linearb.io/platform/cost-capitalization)
- [Dev Team Management — Set targets and tie throughput to business outcomes](https://linearb.io/platform/goals-and-reporting)
- [DevOps Workflow Automation — Policy-based PR routing, approvals, and tests](https://linearb.io/platform/ai-workflow-governance)
- [AI Powered Support — Unify AI and human code delivery in one clear view](https://linearb.io/use-case/ai-powered-support)
- [Optimization — Surface friction with feedback and MCP insights](https://linearb.io/platform/developer-experience)
- [Reporting — Spot what's working and what needs attention](https://linearb.io/use-case/measuring-developer-experience)
- [Surveys — Turn developer feedback into actionable signals](https://linearb.io/platform/developer-surveys)
- [Platform overview](https://linearb.io/platform/overview)
- [Watch now](https://linearb.io/resources/engineering-productivity-gap)
- [Customers](https://linearb.io/customers)
- [Pricing](https://linearb.io/pricing)
- [Why choose LinearB — Explore your data. Measure performance. Act to improve it.](https://linearb.io/why-linearb)
- [APEX framework — The operating model for AI-era engineering teams](https://linearb.io/resources/apex-framework)
- [Anti-FAQ — The questions other vendors won't answer](https://linearb.io/why-linearb/anti-faq)
- [Security — Enterprise-grade compliance and zero code access](https://linearb.io/security)
- [Build vs. buy — The hidden cost of building it yourself](https://linearb.io/resources/build-vs-buy)
- [Dev Interrupted Podcast — Conversations with engineering leaders](https://linearb.io/dev-interrupted/podcasts)
- [Reports & Guides — Deep dives on productivity and delivery](https://linearb.io/resources)
- [Webinars — Expert sessions on productivity and AI](https://linearb.io/resources?category=workshops)
- [Metrics Benchmarks — See how your engineering org stacks up](https://linearb.io/resources/software-engineering-benchmarks-report)
- [Blog — Product updates and practical insights](https://linearb.io/blog)
- [Help Center — Documentation, setup, and support](https://linearb.helpdocs.io)
- [API Docs](https://docs.linearb.io/api-overview)
- [Status](https://www.linearbstatus.com/)
- [Integrations](https://linearb.io/integrations)
- [LinearB Library](https://linearb.io/library)
- [Engineering metrics](https://linearb.io/library/engineering-metrics)
- [Platform engineering](https://linearb.io/library/platform-engineering)
- [Engineering glossary](https://linearb.io/library/engineering-glossary)
- [Developer productivity](https://linearb.io/library/developer-productivity)
- [AI in software development](https://linearb.io/library/ai-in-software-development)
- [Engineering management](https://linearb.io/library/engineering-management)
- [Developer experience](https://linearb.io/library/developer-experience)
- [DevOps](https://linearb.io/library/devops)
- [Engineering operations and the context layer](https://linearb.io/library/engineering-operations)
- [Engineering efficiency](https://linearb.io/library/engineering-efficiency)
- [Software delivery](https://linearb.io/library/software-delivery)
- [Research and data](https://linearb.io/library/engineering-benchmarks-and-research)
- [LinearB is a Leader in the 2026 Gartner® Magic Quadrant™ for Developer Productivity Insight Platforms](https://linearb.io/resources/gartner-magic-quadrant-dpi-platforms-2026)
- [Sign in](https://app.linearb.io/login)
- [Enterprise](https://linearb.io/solutions/enterprise)
- [Contact](https://linearb.io/contact-us)
- [About us](https://linearb.io/about-us)
- [Careers](https://linearb.io/careers)
- [Service agreement](https://linearb.io/services-agreement)
- [Privacy policy](https://linearb.io/privacy-policy)
- [DPA](https://linearb.io/data-processing-agreement)
- [Security FAQ](https://linearb.io/security-faq)
- [Substack](https://devinterrupted.substack.com/)

### Footer

_Additional links from the site footer, not repeated from the top navigation above._

- [GitHub](https://github.com/linear-b)
- [LinkedIn](https://www.linkedin.com/company/linearb)
- [Twitter](https://twitter.com/LinearB_Inc)