Friday, March 14, 2025

Cyclomatic Complexity & Cognitive Complexity in Apex Code

 When writing Apex code in Salesforce, it's important to measure how complex the logic is. Two key metrics for this are:

Cyclomatic Complexity (CC)

Cyclomatic Complexity measures the number of independent paths through a piece of code. It helps estimate how difficult it will be to test and maintain the code.

 How is it Calculated?

Cyclomatic Complexity = (Number of Decision Points) + 1

  • Decision points include if, for, while, switch, and catch statements.

 Example in Apex


public void processAccount(Account acc) { if (acc.Industry == 'Technology') { // 1st decision point acc.Rating = 'Hot'; } else if (acc.Industry == 'Finance') { // 2nd decision point acc.Rating = 'Warm'; } else { acc.Rating = 'Cold'; } }

Cyclomatic Complexity = 3 (2 decision points + 1)

 Why is it Important?

  • High CC (e.g., >10) means the code is difficult to maintain and test.
  • Lower CC values indicate simpler, more maintainable code.

 Cognitive Complexity

Cognitive Complexity measures how difficult a piece of code is to understand for a human reader. Unlike Cyclomatic Complexity, it does not count all decision points equally—it penalizes nested structures and confusing logic more.

 Key Factors Increasing Cognitive Complexity

  • Deeply nested if statements
  • Multiple loops inside loops
  • Complex logical conditions (&&, ||)
  • Recursion & unnecessary method calls

 Example of High Cognitive Complexity


public void processOpportunities(List<Opportunity> opps) { for (Opportunity opp : opps) { // Loop (1 complexity point) if (opp.Amount > 10000) { // Decision point (1) if (opp.StageName == 'Closed Won') { // Nested (penalty) if (opp.Probability == 100) { // Deep nesting (extra penalty) System.debug('Big successful deal!'); } } } } }

Cognitive Complexity is high due to deep nesting.

 Why is it Important?

  • High Cognitive Complexity means developers will struggle to read and modify the code.
  • Keeping it low improves code maintainability and readability.

Key Differences:

MetricCyclomatic Complexity (CC)Cognitive Complexity
MeasuresNumber of decision pathsCode readability & mental effort
FormulaDecisions (if, loops) + 1Penalizes deep nesting & complexity
Focuses onTesting difficultyDeveloper experience
High values indicateHard to test & debugHard to read & maintain
Low values indicateSimpler code structureEasier-to-read code

Best Practices to Reduce Complexity

  • Use early exits (return) instead of deep if nesting
  • Break large methods into smaller ones
  • Use switch-case for better readability
  • Avoid deeply nested loops & conditions
  • Refactor complex logic into helper methods