Skip to content
| Marketplace
Sign in
Visual Studio Code>Programming Languages>Cognitive Complexity for JavaNew to Visual Studio Code? Get it now.
Cognitive Complexity for Java

Cognitive Complexity for Java

hjstephan86

|
21 installs
| (0) | Free
Displays cognitive complexity scores inline for Java methods
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Cognitive Complexity for Java

This Visual Studio Code extension provides a real-time Cognitive Complexity score for Java methods. It helps developers identify hard-to-maintain code by visualizing how difficult a method is to understand based on its nesting and control flow. The extension.js is generated with the help of Claude AI.


Motivation

The following example is taken from https://docs.pmd-code.org/pmd-doc-7.17.0/pmd_rules_java_design.html#cognitivecomplexity and shows how to count the cognitive complexity for each nested statement inside a method consequently:

public class Foo {
  // Has a cognitive complexity of 0
  public void createAccount() {
    Account account = new Account("PMD");
    // save account
  }

  // Has a cognitive complexity of 1
  public Boolean setPhoneNumberIfNotExisting(Account a, String phone) {
    if (a.phone == null) {                                      // +1
      a.phone = phone;
      return true;
    }
    return false;
  }

  // Has a cognitive complexity of 5
  public void updateContacts(List contacts) {
    List contactsToUpdate = new ArrayList();
    for (Contact contact : contacts) {                           // +1
      if (contact.department.equals("Finance")) {                // +2 (nesting = 1)
        contact.title = "Finance Specialist";
        contactsToUpdate.add(contact);
      } else if (contact.department.equals("Sales")) {           // +2
        contact.title = "Sales Specialist";
        contactsToUpdate.add(contact);
      }
    }
    // save contacts
  }
}

Extended Example: Try-Catch Blocks

This extension properly handles try-catch blocks and try-with-resources:

// Has a cognitive complexity of 7
public static String getHash(String input) {
  StringBuilder hexString = new StringBuilder();
  try {                                                        // +1 (nesting = 0)
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] hashBytes = md.digest(input.getBytes());
    
    for (byte b : hashBytes) {                                 // +2 (nesting = 1)
      String hex = Integer.toHexString(0xff & b);
      if (hex.length() == 1) {                                 // +3 (nesting = 2)
        hexString.append('0');
      }
      hexString.append(hex);
    }
  } catch (NoSuchAlgorithmException e) {                       // +1 (nesting = 0)
    LOGGER.log(Level.SEVERE, "Failed: " + e.getMessage(), e);
  }
  return hexString.toString();
}

// Has a cognitive complexity of 11
public static String getFileHash(String algorithm, String filePath) {
  try {                                                        // +1 (nesting = 0)
    MessageDigest digest = MessageDigest.getInstance(algorithm);
    byte[] byteArray = new byte[1024];
    int bytesCount;
    
    try (FileInputStream fis = new FileInputStream(filePath)) {// +2 (nesting = 1, nested try)
      bytesCount = fis.read(byteArray);
      while (bytesCount != -1) {                               // +3 (nesting = 2)
        digest.update(byteArray, 0, bytesCount);
        bytesCount = fis.read(byteArray);
      }
    } catch (IOException e) {                                  // +2 (nesting = 1)
      LOGGER.log(Level.SEVERE, "Failed to read file: " + e.getMessage(), e);
      return null;
    }
    
    byte[] bytes = digest.digest();
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {                                     // +2 (nesting = 1)
      sb.append(String.format("%02x", b));
    }
    return sb.toString();
  } catch (NoSuchAlgorithmException e) {                       // +1 (nesting = 0)
    LOGGER.log(Level.SEVERE, "Failed to compute file hash: " + e.getMessage(), e);
  }
  return null;
}

Features

  • Real-time Analysis: Automatically calculates complexity as you type or switch between Java files.
  • Inline Decorations: Displays the complexity score directly in the editor next to the method declaration in a distinct color (default: purple).
  • Smart Parsing:
    • Recognizes control flow structures: if, else if, else, for, while, do-while, switch, case, try, catch, and ternary operators (? :).
    • Try-with-resources support: Correctly handles try (ResourceType resource = ...) statements.
    • Nested try blocks: Properly accounts for try blocks nested within other try blocks.
    • Nesting awareness: Deeper nested code receives a higher complexity penalty (base +1 plus nesting level).
    • Label handling: Ignores labels like outer: in loop constructs.
    • String literal filtering: Removes string content to avoid false positives from operators in strings.
    • Boolean operators: Each && and || operator is not counted separately, even when multiple appear on the same line.
    • Ignores comments (both // and /* */) and empty lines to ensure accuracy.

Installation

Prerequisites

  • Node.js 20.x or later (recommended)
  • npm and vsce (Visual Studio Code Extension manager)

Install vsce

sudo npm install -g @vscode/vsce

Package and Install

# Navigate to extension directory
cd ~/cogc

# Install dependencies
npm install

# Package the extension
vsce package

# Install in VS Code
code --install-extension cognitive-complexity-java-1.3.4.vsix

Alternative: Manual Installation

If you encounter issues with vsce, you can install manually:

# Create extension directory
mkdir -p ~/.vscode/extensions/cognitive-complexity-java-1.3.4

# Copy files
cp extension.js package.json README.md ~/.vscode/extensions/cognitive-complexity-java-1.3.4/

# Install dependencies
cd ~/.vscode/extensions/cognitive-complexity-java-1.3.4
npm install

# Restart VS Code

Configuration

You can customize the extension via your VS Code Settings (settings.json):

Setting Type Default Description
cognitiveComplexity.enabled boolean true Turns the complexity display on or off.
cognitiveComplexity.color string #9370DB Sets the hex color for the inline text (medium purple).

How to Use

  1. Automatic: Open any .java file. The scores will appear automatically next to your method names in purple text.
  2. Manual: Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and search for:
    Calculate Cognitive Complexity

CSV Report Generation

The extension can generate a comprehensive CSV report of cognitive complexity for all Java files in your project.

How to Generate a Report

  1. Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P)
  2. Type: Generate Cognitive Complexity CSV Report
  3. Wait for the analysis to complete
  4. The report will be saved in your workspace root folder

Report Format

The CSV report contains the following columns:

Column Description
File Relative path to the Java file
Method Name of the method
Start Line Line number where the method starts
End Line Line number where the method ends
Cognitive Complexity Complexity score

Report Features

  • Sorted by complexity: Methods with highest complexity appear first
  • Timestamped filename: Reports are named cognitive-complexity-report-YYYY-MM-DD.csv
  • Summary statistics: Shows total methods, average complexity, and maximum complexity
  • Progress indicator: Visual feedback during analysis
  • Quick open: Option to open the report immediately after generation

Example Report

File,Method,Start Line,End Line,Cognitive Complexity
"src/main/App.java","processComplexData",45,89,23
"src/utils/Parser.java","parseNestedStructure",120,178,18
"src/service/Handler.java","handleRequest",34,67,15

Use Cases

  • Code Review: Identify methods that need refactoring
  • Quality Metrics: Track complexity trends over time
  • Team Analysis: Share complexity reports with team members
  • CI/CD Integration: Export reports for automated quality gates
  • Documentation: Include complexity metrics in project documentation

Requirements

  • VS Code: version 1.80.0 or higher (tested on 1.105.0 with Ubuntu 24.04.3 LTS)
  • Node.js: version 20.x or later recommended
  • Language: Specifically designed for Java source files

Implementation Details

The complexity is calculated based on the following rules:

Base Complexity Rules

  • Structural Increments: +1 for every control flow statement (if, for, while, switch, try, catch, etc.)
  • Nesting Increments: An additional +N for every level of nesting (N = current nesting level)
  • Boolean Logic: Each && and || operator does not add +1

Key Implementation Features

  1. Method-level baseline: The method's opening brace establishes nesting level 0 (does not add to complexity)
  2. Try blocks: try blocks add to complexity (+1 + nesting) and increase nesting for their contents
  3. Try-with-resources: Handles both try { and try (...) syntax correctly
  4. Pattern priority: else if is checked before else to ensure correct matching
  5. Single pattern per line: Only one control flow construct is counted per line
  6. Label exclusion: Labels like outer: do not increase complexity

Calculation Example

For the method getHash(String input) shown above:

try {                    // nesting=0: +1
  for (...) {            // nesting=1: +2
    if (...) {           // nesting=2: +3
    }
  }
} catch (...) {          // nesting=0: +1
}
Total: 1 + 2 + 3 + 1 = 7

Troubleshooting

Extension not working

  1. Check if extension is installed:

    code --list-extensions | grep cognitive
    
  2. View extension logs:

    • Press Ctrl+Shift+P
    • Type: Developer: Show Logs...
    • Select Extension Host
  3. Verify the extension is enabled in Settings

Source Code

  • Extension: https://github.com/hjstephan/cogc
  • Generated with: Claude AI (Anthropic)

Contributing

Contributions are welcome! Please ensure any changes maintain compatibility with the reference Python script.

Visual Studio Code Marketplace

Extension URL: https://marketplace.visualstudio.com/items?itemName=hjstephan86.cognitive-complexity-java

Hub URL: https://marketplace.visualstudio.com/manage/publishers/hjstephan86/extensions/cognitive-complexity-java/hub

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft