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
, andcatch
statements.
Example in Apex
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
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:
Metric | Cyclomatic Complexity (CC) | Cognitive Complexity |
---|---|---|
Measures | Number of decision paths | Code readability & mental effort |
Formula | Decisions (if , loops) + 1 | Penalizes deep nesting & complexity |
Focuses on | Testing difficulty | Developer experience |
High values indicate | Hard to test & debug | Hard to read & maintain |
Low values indicate | Simpler code structure | Easier-to-read code |
Best Practices to Reduce Complexity
- Use early exits (
return
) instead of deepif
nesting - Break large methods into smaller ones
- Use switch-case for better readability
- Avoid deeply nested loops & conditions
- Refactor complex logic into helper methods