Cognitive Complexity for JavaThis 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 MotivationThe 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 BlocksThis extension properly handles
// 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
InstallationPrerequisites
Install vsce
Package and Install
Alternative: Manual InstallationIf you encounter issues with
ConfigurationYou can customize the extension via your VS Code Settings (
How to Use
CSV Report GenerationThe extension can generate a comprehensive CSV report of cognitive complexity for all Java files in your project. How to Generate a Report
Report FormatThe CSV report contains the following columns:
Report Features
Example Report
Use Cases
Requirements
Implementation DetailsThe complexity is calculated based on the following rules: Base Complexity Rules
Key Implementation Features
Calculation ExampleFor the method
TroubleshootingExtension not working
Source Code
ContributingContributions are welcome! Please ensure any changes maintain compatibility with the reference Python script. Visual Studio Code MarketplaceExtension URL: https://marketplace.visualstudio.com/items?itemName=hjstephan86.cognitive-complexity-java |