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

|
4 installs
| (0) | Free
Zeigt die Cognitive Complexity für Java-Methoden mit konsequenter Verschachtelung an
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 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.2.3.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.2.3

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

# Install dependencies
cd ~/.vscode/extensions/cognitive-complexity-java-1.2.3
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

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 adds +(1 + nesting level), counted separately

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/hjstephan86/cogc
  • Generated with: Claude AI (Anthropic)

License

MIT, see https://github.com/hjstephan86/cogc/blob/main/LICENSE

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
© 2025 Microsoft