SlideShare a Scribd company logo
1 of 12
© 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

What's hot

Automation testing introduction for FujiNet
Automation testing introduction for FujiNetAutomation testing introduction for FujiNet
Automation testing introduction for FujiNetHai Tran Son
 
Introduction to Automation Testing
Introduction to Automation TestingIntroduction to Automation Testing
Introduction to Automation TestingArchana Krushnan
 
Agile Testing and Test Automation
Agile Testing and Test AutomationAgile Testing and Test Automation
Agile Testing and Test AutomationNaveen Kumar Singh
 
Test automation
Test automationTest automation
Test automationXavier Yin
 
Pipeline based deployments on Jenkins
Pipeline based deployments  on JenkinsPipeline based deployments  on Jenkins
Pipeline based deployments on JenkinsKnoldus Inc.
 
Hybrid Automation Framework Development introduction
Hybrid Automation Framework Development introductionHybrid Automation Framework Development introduction
Hybrid Automation Framework Development introductionGanuka Yashantha
 
Introduction to Robot Framework (external)
Introduction to Robot Framework (external)Introduction to Robot Framework (external)
Introduction to Robot Framework (external)Zhe Li
 
Testing Tool Evaluation Criteria
Testing Tool Evaluation CriteriaTesting Tool Evaluation Criteria
Testing Tool Evaluation Criteriabasma_iti_1984
 
Test Process Improvement
Test Process ImprovementTest Process Improvement
Test Process ImprovementMomentum NI
 
[Infographic] Challenges in Test Automation
[Infographic] Challenges in Test Automation [Infographic] Challenges in Test Automation
[Infographic] Challenges in Test Automation Katalon Studio
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Automated vs manual testing
Automated vs manual testingAutomated vs manual testing
Automated vs manual testingKanoah
 
Test driven development
Test driven developmentTest driven development
Test driven developmentNascenia IT
 

What's hot (20)

Automation testing introduction for FujiNet
Automation testing introduction for FujiNetAutomation testing introduction for FujiNet
Automation testing introduction for FujiNet
 
Introduction to Automation Testing
Introduction to Automation TestingIntroduction to Automation Testing
Introduction to Automation Testing
 
Agile Testing and Test Automation
Agile Testing and Test AutomationAgile Testing and Test Automation
Agile Testing and Test Automation
 
Test automation
Test automationTest automation
Test automation
 
Testing methodology
Testing methodologyTesting methodology
Testing methodology
 
Pipeline based deployments on Jenkins
Pipeline based deployments  on JenkinsPipeline based deployments  on Jenkins
Pipeline based deployments on Jenkins
 
Junit
JunitJunit
Junit
 
Hybrid Automation Framework Development introduction
Hybrid Automation Framework Development introductionHybrid Automation Framework Development introduction
Hybrid Automation Framework Development introduction
 
Introduction to Robot Framework (external)
Introduction to Robot Framework (external)Introduction to Robot Framework (external)
Introduction to Robot Framework (external)
 
Testing Tool Evaluation Criteria
Testing Tool Evaluation CriteriaTesting Tool Evaluation Criteria
Testing Tool Evaluation Criteria
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Uft Basics
Uft BasicsUft Basics
Uft Basics
 
Test Process Improvement
Test Process ImprovementTest Process Improvement
Test Process Improvement
 
[Infographic] Challenges in Test Automation
[Infographic] Challenges in Test Automation [Infographic] Challenges in Test Automation
[Infographic] Challenges in Test Automation
 
Types of testing
Types of testingTypes of testing
Types of testing
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Test Plan.pptx
Test Plan.pptxTest Plan.pptx
Test Plan.pptx
 
Automated vs manual testing
Automated vs manual testingAutomated vs manual testing
Automated vs manual testing
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test Automation - Keytorc Approach
Test Automation - Keytorc Approach Test Automation - Keytorc Approach
Test Automation - Keytorc Approach
 

Similar to Cyclomatic and cognitive complexity

Machine learning testing survey, landscapes and horizons, the Cliff Notes
Machine learning testing  survey, landscapes and horizons, the Cliff NotesMachine learning testing  survey, landscapes and horizons, the Cliff Notes
Machine learning testing survey, landscapes and horizons, the Cliff NotesHeemeng Foo
 
Navy Training Scheduling - Euro 2021
Navy Training Scheduling - Euro 2021 Navy Training Scheduling - Euro 2021
Navy Training Scheduling - Euro 2021 Eray Cakici
 
Technical debt management strategies
Technical debt management strategiesTechnical debt management strategies
Technical debt management strategiesRaquel Pau
 
Cost estimation using cocomo model
Cost estimation using cocomo modelCost estimation using cocomo model
Cost estimation using cocomo modelNitesh Bichwani
 
In Depth Constructive Cost Modeling related slides
In Depth Constructive Cost Modeling related slidesIn Depth Constructive Cost Modeling related slides
In Depth Constructive Cost Modeling related slidesChobodiDamsaraniPadm
 
PRG/211 ENTIRE CLASS UOP TUTORIALS
PRG/211 ENTIRE CLASS UOP TUTORIALSPRG/211 ENTIRE CLASS UOP TUTORIALS
PRG/211 ENTIRE CLASS UOP TUTORIALSSharon Reynolds
 
Overview1) Overview – The continued discussion of project implem.docx
Overview1) Overview – The continued discussion of project implem.docxOverview1) Overview – The continued discussion of project implem.docx
Overview1) Overview – The continued discussion of project implem.docxalfred4lewis58146
 
Overview1) Overview – The continued discussion of .docx
Overview1)             Overview – The continued discussion of .docxOverview1)             Overview – The continued discussion of .docx
Overview1) Overview – The continued discussion of .docxalfred4lewis58146
 
COCOMO methods for software size estimation
COCOMO methods for software size estimationCOCOMO methods for software size estimation
COCOMO methods for software size estimationPramod Parajuli
 
Towards a formal analysis of the multi-robot task allocation problem using se...
Towards a formal analysis of the multi-robot task allocation problem using se...Towards a formal analysis of the multi-robot task allocation problem using se...
Towards a formal analysis of the multi-robot task allocation problem using se...journalBEEI
 
The working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор ТурскийThe working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор ТурскийSigma Software
 
The working architecture of node js applications open tech week javascript ...
The working architecture of node js applications   open tech week javascript ...The working architecture of node js applications   open tech week javascript ...
The working architecture of node js applications open tech week javascript ...Viktor Turskyi
 
Yagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docx
Yagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docxYagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docx
Yagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docxjeffevans62972
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
Refactoring Big Design Smells : Presented by Sanjay Kumar
Refactoring Big Design Smells : Presented by Sanjay KumarRefactoring Big Design Smells : Presented by Sanjay Kumar
Refactoring Big Design Smells : Presented by Sanjay KumaroGuild .
 

Similar to Cyclomatic and cognitive complexity (20)

Machine learning testing survey, landscapes and horizons, the Cliff Notes
Machine learning testing  survey, landscapes and horizons, the Cliff NotesMachine learning testing  survey, landscapes and horizons, the Cliff Notes
Machine learning testing survey, landscapes and horizons, the Cliff Notes
 
Navy Training Scheduling - Euro 2021
Navy Training Scheduling - Euro 2021 Navy Training Scheduling - Euro 2021
Navy Training Scheduling - Euro 2021
 
Technical debt management strategies
Technical debt management strategiesTechnical debt management strategies
Technical debt management strategies
 
Cost estimation using cocomo model
Cost estimation using cocomo modelCost estimation using cocomo model
Cost estimation using cocomo model
 
In Depth Constructive Cost Modeling related slides
In Depth Constructive Cost Modeling related slidesIn Depth Constructive Cost Modeling related slides
In Depth Constructive Cost Modeling related slides
 
Metrics
MetricsMetrics
Metrics
 
PRG/211 ENTIRE CLASS UOP TUTORIALS
PRG/211 ENTIRE CLASS UOP TUTORIALSPRG/211 ENTIRE CLASS UOP TUTORIALS
PRG/211 ENTIRE CLASS UOP TUTORIALS
 
Bof4162 kovalsky
Bof4162 kovalskyBof4162 kovalsky
Bof4162 kovalsky
 
COCOMO MODEL
COCOMO MODELCOCOMO MODEL
COCOMO MODEL
 
Overview1) Overview – The continued discussion of project implem.docx
Overview1) Overview – The continued discussion of project implem.docxOverview1) Overview – The continued discussion of project implem.docx
Overview1) Overview – The continued discussion of project implem.docx
 
Overview1) Overview – The continued discussion of .docx
Overview1)             Overview – The continued discussion of .docxOverview1)             Overview – The continued discussion of .docx
Overview1) Overview – The continued discussion of .docx
 
COCOMO Model By Dr. B. J. Mohite
COCOMO Model By Dr. B. J. MohiteCOCOMO Model By Dr. B. J. Mohite
COCOMO Model By Dr. B. J. Mohite
 
ewili13_submission_14
ewili13_submission_14ewili13_submission_14
ewili13_submission_14
 
COCOMO methods for software size estimation
COCOMO methods for software size estimationCOCOMO methods for software size estimation
COCOMO methods for software size estimation
 
Towards a formal analysis of the multi-robot task allocation problem using se...
Towards a formal analysis of the multi-robot task allocation problem using se...Towards a formal analysis of the multi-robot task allocation problem using se...
Towards a formal analysis of the multi-robot task allocation problem using se...
 
The working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор ТурскийThe working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор Турский
 
The working architecture of node js applications open tech week javascript ...
The working architecture of node js applications   open tech week javascript ...The working architecture of node js applications   open tech week javascript ...
The working architecture of node js applications open tech week javascript ...
 
Yagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docx
Yagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docxYagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docx
Yagmur Bostanci47 Hackensack Street, East Rutherford, NJ929-22.docx
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Refactoring Big Design Smells : Presented by Sanjay Kumar
Refactoring Big Design Smells : Presented by Sanjay KumarRefactoring Big Design Smells : Presented by Sanjay Kumar
Refactoring Big Design Smells : Presented by Sanjay Kumar
 

Recently uploaded

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Recently uploaded (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

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