Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to maintain.
A developer can reduce the Cognitive Complexity in following ways.
- Deep nesting: Use early returns or guard clauses
- Repeated logic: Extract into helper functions
- Multiple concerns: Break the method into smaller methods
- Verbose conditions: Use descriptive variable/method names
A Java code example with high cognitive complexity
This is a Java code example, that is nested, hard-to-read method that checks prime numbers, counts them, and handles edge cases.public int countPrimes(int[] numbers) { int count = 0; for (int i = 0; i < numbers.length; i++) { if (numbers[i] > 1) { boolean isPrime = true; for (int j = 2; j < numbers[i]; j++) { if (numbers[i] % j == 0) { isPrime = false; break; } } if (isPrime) { count++; } } else { if (numbers[i] == 0) { System.out.println("Zero found"); } else { System.out.println("Negative or One found"); } } } return count; }
Refactored the above java code (low congitive complexity)
public int countPrimes(int[] numbers) { int count = 0; for (int num : numbers) { if (isPrime(num)) { count++; } else { handleNonPrime(num); } } return count; } private boolean isPrime(int num) { if (num <= 1) return false; for (int i = 2; i < num; i++) { if (num % i == 0) return false; } return true; } private void handleNonPrime(int num) { if (num == 0) { System.out.println("Zero found"); } else { System.out.println("Negative or One found"); } }