SlideShare a Scribd company logo
2
Most read
3
Most read
5
Most read
© 2020 Hee-Meng Foo
Cyclomatic & Cognitive
Complexity
Hee-Meng Foo, April 2020
© 2020 Hee-Meng Foo
What is Cyclomatic Complexity
● Proposed by Thomas McCabe in 1976 to measure how complex a piece of
code is
○ Complexity - measure of testability and maintainability of a piece of code
○ Main idea
■ build a DAG representing the control flow of a function/module - Control Flow Graph (CFG)
■ Measure the number of linearly independent paths through the code
○ Formula: M = E - N + 2P
● Historical context: this was the time of BASIC, ALGOL, FORTRAN, COBOL
○ The dreaded GOTO statement
● Correlates to number of defects (see Wikipedia for references)
● Relates to testing
○ It provides an upper bound to the num of test cases to achieve complete branch coverage
○ It provides a lower bound to the num of test cases for path coverage
© 2020 Hee-Meng Foo
Building the CFG (Control Flow Graph)
© 2020 Hee-Meng Foo
Calculating the Cyclomatic Complexity
M = E - N + 2P
E = num edges
N = num nodes
P = num connected components
M = 11 - 9 + 2(1)
= 4
© 2020 Hee-Meng Foo
Calculating the Cyclomatic Complexity
M = num of flow control cmds + 1
= 3 + 1 = 4
Watch the YouTube video found in References [6]
© 2020 Hee-Meng Foo
More examples of Control Flows
Source: YouTube (see References [1])
© 2020 Hee-Meng Foo
Rule of Thumb
● 1-10 : simple function, not much risk
● 11-20 : Moderate risk
● 21-50 : High risk
● > 50 : really bad
Source: http://www.ganssle.com/articles/cyclomaticcomplexity.html
© 2020 Hee-Meng Foo
What is Cognitive Complexity
● Proposed by G. Ann Campbell of SonarSource (2018)
● The problem with Cyclomatic Complexity:
○ Addresses testability but not maintainability
○ Does not take into account modern code constructs like switch, try-catch, lambdas, ternary
operators in making code easier to comprehend (hence cognitive complexity)
○ OOP: a class with many easily maintained methods may have same complexity as a class with
1 method with high complexity
“If you’re having to fix a P0 at 3am in the morning, what kind of code would you like
to be troubleshooting?”
© 2020 Hee-Meng Foo
Differences in Calculation
1. Ternary operators add 0 to the complexity
a. eg. boolean a = x > y ? true : false
b. The equivalent if-else will add 1
2. Switch statements only add 1 to the complexity regardless of num cases
3. Try-catch statements add 1 to complexity regardless of num catches
4. Predicates:
a. If you break the linear flow, you add to complexity
b. Eg. (a && b && c) adds 1 but (a && b || c) adds 2
5. continue, break don’t add to complexity
6. Nested flows accumulate
Source: YouTube (see References [5])
© 2020 Hee-Meng Foo
Differences in Calculation
Class Methods
Source: SonarSource Blog (see References [7])
© 2020 Hee-Meng Foo
So How Do You Apply Cyclomatic & Cognitive Complexity?
● Should they be used as gating criteria?
Probably not. There are many reasons why code is sometimes complex.
Of course a high complexity number of ~ 50 should raise some red flags
● Should they be used as input to Code Reviews?
Most definitely. The principle of enlightened self interest should hold.
In other words, if you do not want to debug/maintain highly complex code, you
should call it out when reviewing PRs.
● Should you prioritize tests based on complexity?
Most definitely. The more complex the code, the more it needs bubble wrap!
© 2020 Hee-Meng Foo
References
1. Wikipedia entry on Cyclomatic Complexity -
https://en.wikipedia.org/wiki/Cyclomatic_complexity
2. YouTube: Cyclomatic Complexity for Developers by Jeroen Resoort
(https://youtu.be/JwTQywqpZ5Y)
3. Taming Complexity by Jack Ganssle -
http://www.ganssle.com/articles/cyclomaticcomplexity.html
4. Cognitive Complexity: A new way of measuring understandability by G. Ann Campbell -
https://www.sonarsource.com/docs/CognitiveComplexity.pdf
5. YouTube: Time to learn Cognitive Complexity by Yashish Dua (https://youtu.be/r-
LCSRxJSMI)
6. YouTube: Cyclomatic Complexity in Software Engineering with Trick by Arora Education
(https://youtu.be/PlCGomvu-NM)
7. SonarSource Blog on Cyclomatic Complexity - https://blog.sonarsource.com/cognitive-
complexity-because-testability-understandability

More Related Content

PPT
Software Testing 101
PDF
Revised IEEE 1633 Recommended Practices for Software Reliability
PPTX
Stlc ppt
PPSX
PDF
Software Testing - Defect/Bug Life Cycle - Complete Flow Chart of Defect States
PPTX
Regression testing
PPT
PDF
What is Regression Testing? | Edureka
Software Testing 101
Revised IEEE 1633 Recommended Practices for Software Reliability
Stlc ppt
Software Testing - Defect/Bug Life Cycle - Complete Flow Chart of Defect States
Regression testing
What is Regression Testing? | Edureka

What's hot (20)

PPTX
Software testing principles
PPT
Testing fundamentals
PPTX
Formulating Agile Testing Strategy
PPSX
Principles of Software testing
PPTX
TestNG Framework
PPTX
Introduction to Automation Testing
PPTX
Regression testing
DOC
Manual testing real time questions by subbu
PPTX
Unit Testing
PPT
Software testing basic concepts
PPTX
STLC-ppt-1.pptx
PPT
Basic software-testing-concepts
PPT
Software Development Life Cycle (SDLC)
PDF
Fundamentals of Software Testing
PDF
Java 8 ​and ​Best Practices
PDF
What is integration testing
PDF
Mutation Testing
PPT
Software Testing
PDF
Mutation testing (OOP 2012, 2012-JAN-24)
PDF
Automation testing introduction for FujiNet
Software testing principles
Testing fundamentals
Formulating Agile Testing Strategy
Principles of Software testing
TestNG Framework
Introduction to Automation Testing
Regression testing
Manual testing real time questions by subbu
Unit Testing
Software testing basic concepts
STLC-ppt-1.pptx
Basic software-testing-concepts
Software Development Life Cycle (SDLC)
Fundamentals of Software Testing
Java 8 ​and ​Best Practices
What is integration testing
Mutation Testing
Software Testing
Mutation testing (OOP 2012, 2012-JAN-24)
Automation testing introduction for FujiNet
Ad

Similar to Cyclomatic and cognitive complexity (20)

PPTX
Machine learning testing survey, landscapes and horizons, the Cliff Notes
PDF
Navy Training Scheduling - Euro 2021
PDF
Technical debt management strategies
PPT
Cocomo Model Presentation Software Engineering, MAKUT
PPTX
Cost estimation using cocomo model
PPTX
In Depth Constructive Cost Modeling related slides
PPT
Metrics
PDF
PRG/211 ENTIRE CLASS UOP TUTORIALS
PDF
Bof4162 kovalsky
PPT
COCOMO MODEL
DOCX
Overview1) Overview – The continued discussion of project implem.docx
DOCX
Overview1) Overview – The continued discussion of .docx
PDF
COCOMO Model By Dr. B. J. Mohite
PDF
ewili13_submission_14
PDF
COCOMO methods for software size estimation
PDF
Towards a formal analysis of the multi-robot task allocation problem using se...
PDF
The working architecture of NodeJS applications, Виктор Турский
PDF
The working architecture of node js applications open tech week javascript ...
PPTX
Improving Code Quality Through Effective Review Process
PDF
Project Management dksfjhksjdhfwfjsd.pdf
Machine learning testing survey, landscapes and horizons, the Cliff Notes
Navy Training Scheduling - Euro 2021
Technical debt management strategies
Cocomo Model Presentation Software Engineering, MAKUT
Cost estimation using cocomo model
In Depth Constructive Cost Modeling related slides
Metrics
PRG/211 ENTIRE CLASS UOP TUTORIALS
Bof4162 kovalsky
COCOMO MODEL
Overview1) Overview – The continued discussion of project implem.docx
Overview1) Overview – The continued discussion of .docx
COCOMO Model By Dr. B. J. Mohite
ewili13_submission_14
COCOMO methods for software size estimation
Towards a formal analysis of the multi-robot task allocation problem using se...
The working architecture of NodeJS applications, Виктор Турский
The working architecture of node js applications open tech week javascript ...
Improving Code Quality Through Effective Review Process
Project Management dksfjhksjdhfwfjsd.pdf
Ad

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Nekopoi APK 2025 free lastest update
PDF
System and Network Administraation Chapter 3
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
history of c programming in notes for students .pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Introduction to Artificial Intelligence
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Digital Strategies for Manufacturing Companies
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Operating system designcfffgfgggggggvggggggggg
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Nekopoi APK 2025 free lastest update
System and Network Administraation Chapter 3
Reimagine Home Health with the Power of Agentic AI​
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Computer Software and OS of computer science of grade 11.pptx
Design an Analysis of Algorithms II-SECS-1021-03
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
history of c programming in notes for students .pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Introduction to Artificial Intelligence
CHAPTER 2 - PM Management and IT Context
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Digital Strategies for Manufacturing Companies
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Adobe Illustrator 28.6 Crack My Vision of Vector Design

Cyclomatic and cognitive complexity

  • 1. © 2020 Hee-Meng Foo Cyclomatic & Cognitive Complexity Hee-Meng Foo, April 2020
  • 2. © 2020 Hee-Meng Foo What is Cyclomatic Complexity ● Proposed by Thomas McCabe in 1976 to measure how complex a piece of code is ○ Complexity - measure of testability and maintainability of a piece of code ○ Main idea ■ build a DAG representing the control flow of a function/module - Control Flow Graph (CFG) ■ Measure the number of linearly independent paths through the code ○ Formula: M = E - N + 2P ● Historical context: this was the time of BASIC, ALGOL, FORTRAN, COBOL ○ The dreaded GOTO statement ● Correlates to number of defects (see Wikipedia for references) ● Relates to testing ○ It provides an upper bound to the num of test cases to achieve complete branch coverage ○ It provides a lower bound to the num of test cases for path coverage
  • 3. © 2020 Hee-Meng Foo Building the CFG (Control Flow Graph)
  • 4. © 2020 Hee-Meng Foo Calculating the Cyclomatic Complexity M = E - N + 2P E = num edges N = num nodes P = num connected components M = 11 - 9 + 2(1) = 4
  • 5. © 2020 Hee-Meng Foo Calculating the Cyclomatic Complexity M = num of flow control cmds + 1 = 3 + 1 = 4 Watch the YouTube video found in References [6]
  • 6. © 2020 Hee-Meng Foo More examples of Control Flows Source: YouTube (see References [1])
  • 7. © 2020 Hee-Meng Foo Rule of Thumb ● 1-10 : simple function, not much risk ● 11-20 : Moderate risk ● 21-50 : High risk ● > 50 : really bad Source: http://www.ganssle.com/articles/cyclomaticcomplexity.html
  • 8. © 2020 Hee-Meng Foo What is Cognitive Complexity ● Proposed by G. Ann Campbell of SonarSource (2018) ● The problem with Cyclomatic Complexity: ○ Addresses testability but not maintainability ○ Does not take into account modern code constructs like switch, try-catch, lambdas, ternary operators in making code easier to comprehend (hence cognitive complexity) ○ OOP: a class with many easily maintained methods may have same complexity as a class with 1 method with high complexity “If you’re having to fix a P0 at 3am in the morning, what kind of code would you like to be troubleshooting?”
  • 9. © 2020 Hee-Meng Foo Differences in Calculation 1. Ternary operators add 0 to the complexity a. eg. boolean a = x > y ? true : false b. The equivalent if-else will add 1 2. Switch statements only add 1 to the complexity regardless of num cases 3. Try-catch statements add 1 to complexity regardless of num catches 4. Predicates: a. If you break the linear flow, you add to complexity b. Eg. (a && b && c) adds 1 but (a && b || c) adds 2 5. continue, break don’t add to complexity 6. Nested flows accumulate Source: YouTube (see References [5])
  • 10. © 2020 Hee-Meng Foo Differences in Calculation Class Methods Source: SonarSource Blog (see References [7])
  • 11. © 2020 Hee-Meng Foo So How Do You Apply Cyclomatic & Cognitive Complexity? ● Should they be used as gating criteria? Probably not. There are many reasons why code is sometimes complex. Of course a high complexity number of ~ 50 should raise some red flags ● Should they be used as input to Code Reviews? Most definitely. The principle of enlightened self interest should hold. In other words, if you do not want to debug/maintain highly complex code, you should call it out when reviewing PRs. ● Should you prioritize tests based on complexity? Most definitely. The more complex the code, the more it needs bubble wrap!
  • 12. © 2020 Hee-Meng Foo References 1. Wikipedia entry on Cyclomatic Complexity - https://en.wikipedia.org/wiki/Cyclomatic_complexity 2. YouTube: Cyclomatic Complexity for Developers by Jeroen Resoort (https://youtu.be/JwTQywqpZ5Y) 3. Taming Complexity by Jack Ganssle - http://www.ganssle.com/articles/cyclomaticcomplexity.html 4. Cognitive Complexity: A new way of measuring understandability by G. Ann Campbell - https://www.sonarsource.com/docs/CognitiveComplexity.pdf 5. YouTube: Time to learn Cognitive Complexity by Yashish Dua (https://youtu.be/r- LCSRxJSMI) 6. YouTube: Cyclomatic Complexity in Software Engineering with Trick by Arora Education (https://youtu.be/PlCGomvu-NM) 7. SonarSource Blog on Cyclomatic Complexity - https://blog.sonarsource.com/cognitive- complexity-because-testability-understandability