SlideShare a Scribd company logo
1 of 23
Download to read offline
Code
Complexity 101
Arun Saha, Ph.D.
arunksaha AT gmail DOT com
(A pragmatic programmer and a software craftsman)
https://www.linkedin.com/in/arunksaha
Complexity Kills
What
November 2014 Code Complexity 101 2
Sphaghetti Junction
(Bitter) Fact of life:
Code complexity keeps increasing
What
November 2014 Code Complexity 101 3
(Bitter) Fact of life:
Code complexity keeps increasing
What
November 2014 Code Complexity 101 4
How to measure code complexity
objectively?
Simple Objective Metric:
Cyclomatic Complexity
What
November 2014 Code Complexity 101 5
Developed by Thomas J. McCabe Sr. in 1976
Also known as McCabe Complexity
Definition and Theory: http://en.wikipedia.org/wiki/Cyclomatic_complexity
Cyclomatic Complexity of a Function,
M = E – N + 1
Where, E = # of edges, N = # of nodes
Details
November 2014 Code Complexity 101 6
if (c1())
f1();
else
f2();
if (c2())
f3();
else
f4();
M = 9 – 7 + 1 = 3
Informally,
Complexity of a module*:
sum of complexities of its functions
* e.g. *.c, *.cc file
November 2014 Code Complexity 101 7
What
Complexity of a function:
M = E – N + 1
How
November 2014 Code Complexity 101 8
Lower bound:
# of conditionals
For example, in C and C++, each of the following keywords increase the
complexity by 1
return, if, for, while, &&, ||, ?:, case,
goto, break, continue
FYI
November 2014 Code Complexity 101 9
however,
Calling function does not increase complexity of either
the caller or the callee
FYI
November 2014 Code Complexity 101 10
however,
Calling function does not increase complexity of either
the caller or the callee
Caveat
November 2014 Code Complexity 101 11
McCabe Complexity != Big O Complexity
They are totally completely different.
Example 1
// Two functions of complexity 1
int c1_direct( int x ) {
return x + 1;
}
int c1_redirect( int x ) {
int const result = add( x, 1 );
return result;
}
E.g.
November 2014 Code Complexity 101 12
Example 2
// complexity: 2
// 1 for “return”, 1 for “?:”
int c2_min( int x, int y ) {
return y < x ? y : x;
}
E.g.
November 2014 Code Complexity 101 13
Example 3
// complexity: 3
// 1 for “if”, 1 for each “return”
int c3_min( int x, int y ) {
if( y < x ) {
return y;
}
else {
return x;
}
}
E.g.
November 2014 Code Complexity 101 14
Example 4
// complexity: 3
// 1 for “return”, 1 for “&&”, 1 for “?:”
int c4_bothtrue( int x, int y ) {
return (x && y) ? 1 : 0;
}
E.g.
November 2014 Code Complexity 101 15
Same function can be (correctly) written with different
complexities.
FYI
November 2014 Code Complexity 101 16
Example 5.1
Problem BothNonZero: Given two int’s, return
non-zero if both are non-zero, zero otherwise.
// BothNonZero: Approach 1, Complexity: 4
int bothNonZero_1( int x, int y ) {
if( x ) {
if( y ) {
return 1;
}
}
return 0;
}
E.g.
November 2014 Code Complexity 101 17
Example 5.2
// BothNonZero: Approach 2, Complexity: 4
int bothNonZero_2( int x, int y ) {
if( x && y ) {
return 1;
}
return 0;
}
E.g.
November 2014 Code Complexity 101 18
Example 5.3
// BothNonZero: Approach 3, Complexity: 2
int bothNonZero_3( int x, int y ) {
return x && y;
}
E.g.
November 2014 Code Complexity 101 19
FYI
November 2014 Code Complexity 101 20
A common application is to compare the measured
complexity against a set of threshold values. One such
threshold set is as follows
Cyclomatic Complexity Risk Evaluation
1 – 10 A simple program, without much risk
11 – 20 More complex, moderate risk
21 – 50 Complex, high risk program
51 + Unstable program (very high risk)
Source: http://www.sei.cmu.edu/reports/97hb001.pdf p. 145
Fine, but how complex is really complex?
Dev Team:
Where should I
prioritize my
refactoring?
Benefits
November 2014 Code Complexity 101 21
QA Team:
Where should I
prioritize my testing?
FYI
November 2014 Code Complexity 101 22
I use CCCC
http://sourceforge.net/projects/cccc/files/cccc/3.1.4/
with my simple wrapper mccabe.sh
(available at)
https://github.com/arunksaha/complexity
(contains the function examples used here)
Great, how can I get started today?
November 2014 Code Complexity 101 23

More Related Content

What's hot

Why API Ops is the Next Wave of DevOps
Why API Ops is the Next Wave of DevOpsWhy API Ops is the Next Wave of DevOps
Why API Ops is the Next Wave of DevOpsJohn Musser
 
Application Monitoring using Datadog
Application Monitoring using DatadogApplication Monitoring using Datadog
Application Monitoring using DatadogMukta Aphale
 
The Architecture of an API Platform
The Architecture of an API PlatformThe Architecture of an API Platform
The Architecture of an API PlatformJohannes Ridderstedt
 
Introduction to AWS Amplify and the Amplify CLI Toolchain
Introduction to AWS Amplify and the Amplify CLI ToolchainIntroduction to AWS Amplify and the Amplify CLI Toolchain
Introduction to AWS Amplify and the Amplify CLI ToolchainAWS Germany
 
Lecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software EngineeringLecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software EngineeringAchmad Solichin
 
I Love APIs 2015: Crash Course Foundational Topics in Apigee Edge Workshop
I Love APIs 2015: Crash Course Foundational Topics in Apigee Edge WorkshopI Love APIs 2015: Crash Course Foundational Topics in Apigee Edge Workshop
I Love APIs 2015: Crash Course Foundational Topics in Apigee Edge WorkshopApigee | Google Cloud
 
Software process and project metrics
Software process and project metricsSoftware process and project metrics
Software process and project metricsIndu Sharma Bhardwaj
 
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...Edureka!
 
CI/CD (DevOps) 101
CI/CD (DevOps) 101CI/CD (DevOps) 101
CI/CD (DevOps) 101Hazzim Anaya
 
Future of Integration | MuleSoft
Future of Integration | MuleSoftFuture of Integration | MuleSoft
Future of Integration | MuleSoftMuleSoft
 
Programming paradigm and web programming
Programming paradigm and web programmingProgramming paradigm and web programming
Programming paradigm and web programmingMohammad Kamrul Hasan
 
Dev ops != Dev+Ops
Dev ops != Dev+OpsDev ops != Dev+Ops
Dev ops != Dev+OpsShalu Ahuja
 
API Best Practices
API Best PracticesAPI Best Practices
API Best PracticesSai Koppala
 
Software Defined Network - SDN
Software Defined Network - SDNSoftware Defined Network - SDN
Software Defined Network - SDNVenkata Naga Ravi
 
Workshop: An Introduction to API Automation with Javascript
Workshop: An Introduction to API Automation with JavascriptWorkshop: An Introduction to API Automation with Javascript
Workshop: An Introduction to API Automation with JavascriptApplitools
 

What's hot (20)

Why API Ops is the Next Wave of DevOps
Why API Ops is the Next Wave of DevOpsWhy API Ops is the Next Wave of DevOps
Why API Ops is the Next Wave of DevOps
 
Application Monitoring using Datadog
Application Monitoring using DatadogApplication Monitoring using Datadog
Application Monitoring using Datadog
 
The Architecture of an API Platform
The Architecture of an API PlatformThe Architecture of an API Platform
The Architecture of an API Platform
 
Introduction to AWS Amplify and the Amplify CLI Toolchain
Introduction to AWS Amplify and the Amplify CLI ToolchainIntroduction to AWS Amplify and the Amplify CLI Toolchain
Introduction to AWS Amplify and the Amplify CLI Toolchain
 
Lecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software EngineeringLecture 01 Introduction to Software Engineering
Lecture 01 Introduction to Software Engineering
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
 
I Love APIs 2015: Crash Course Foundational Topics in Apigee Edge Workshop
I Love APIs 2015: Crash Course Foundational Topics in Apigee Edge WorkshopI Love APIs 2015: Crash Course Foundational Topics in Apigee Edge Workshop
I Love APIs 2015: Crash Course Foundational Topics in Apigee Edge Workshop
 
Software process and project metrics
Software process and project metricsSoftware process and project metrics
Software process and project metrics
 
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
What is DevOps | DevOps Introduction | DevOps Training | DevOps Tutorial | Ed...
 
CI/CD (DevOps) 101
CI/CD (DevOps) 101CI/CD (DevOps) 101
CI/CD (DevOps) 101
 
Opc ua
Opc uaOpc ua
Opc ua
 
Future of Integration | MuleSoft
Future of Integration | MuleSoftFuture of Integration | MuleSoft
Future of Integration | MuleSoft
 
Programming paradigm and web programming
Programming paradigm and web programmingProgramming paradigm and web programming
Programming paradigm and web programming
 
Devops
DevopsDevops
Devops
 
Dev ops != Dev+Ops
Dev ops != Dev+OpsDev ops != Dev+Ops
Dev ops != Dev+Ops
 
Agile vs dev ops
Agile vs dev opsAgile vs dev ops
Agile vs dev ops
 
API Best Practices
API Best PracticesAPI Best Practices
API Best Practices
 
Software Defined Network - SDN
Software Defined Network - SDNSoftware Defined Network - SDN
Software Defined Network - SDN
 
Workshop: An Introduction to API Automation with Javascript
Workshop: An Introduction to API Automation with JavascriptWorkshop: An Introduction to API Automation with Javascript
Workshop: An Introduction to API Automation with Javascript
 
"DevOps > CI+CD "
"DevOps > CI+CD ""DevOps > CI+CD "
"DevOps > CI+CD "
 

Viewers also liked

Touchless Enum to String in C
Touchless Enum to String in CTouchless Enum to String in C
Touchless Enum to String in CArun Saha
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedDennis de Greef
 
Using cyclomatic complexity to measure code complexity
Using cyclomatic complexity to measure code complexityUsing cyclomatic complexity to measure code complexity
Using cyclomatic complexity to measure code complexityJane Chung
 
Example of-method-with-cyclomatic-complexity-17
Example of-method-with-cyclomatic-complexity-17Example of-method-with-cyclomatic-complexity-17
Example of-method-with-cyclomatic-complexity-17Zarko Acimovic
 
Certificación Zend PHP 5.3 - Alejandro Mohamad
Certificación Zend PHP 5.3 - Alejandro MohamadCertificación Zend PHP 5.3 - Alejandro Mohamad
Certificación Zend PHP 5.3 - Alejandro MohamadPablo Ignacio de la Vega
 
Mule functional, blackbox, unit testing
Mule functional, blackbox, unit testingMule functional, blackbox, unit testing
Mule functional, blackbox, unit testingveena naresh
 
Implementing Blackbox Testing
Implementing Blackbox TestingImplementing Blackbox Testing
Implementing Blackbox TestingEdureka!
 
Structural testing
Structural testingStructural testing
Structural testingSlideshare
 
Control Flow Testing
Control Flow TestingControl Flow Testing
Control Flow TestingHirra Sultan
 
Structural and functional testing
Structural and functional testingStructural and functional testing
Structural and functional testingHimanshu
 
Basis path testing
Basis path testingBasis path testing
Basis path testingHoa Le
 
01 software test engineering (manual testing)
01 software test engineering (manual testing)01 software test engineering (manual testing)
01 software test engineering (manual testing)Siddireddy Balu
 
Chapter 8 software testing
Chapter 8 software testingChapter 8 software testing
Chapter 8 software testingdespicable me
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence Yasir Khan
 
Knowledge representation in AI
Knowledge representation in AIKnowledge representation in AI
Knowledge representation in AIVishal Singh
 

Viewers also liked (20)

Touchless Enum to String in C
Touchless Enum to String in CTouchless Enum to String in C
Touchless Enum to String in C
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explained
 
Using cyclomatic complexity to measure code complexity
Using cyclomatic complexity to measure code complexityUsing cyclomatic complexity to measure code complexity
Using cyclomatic complexity to measure code complexity
 
Example of-method-with-cyclomatic-complexity-17
Example of-method-with-cyclomatic-complexity-17Example of-method-with-cyclomatic-complexity-17
Example of-method-with-cyclomatic-complexity-17
 
Certificación Zend PHP 5.3 - Alejandro Mohamad
Certificación Zend PHP 5.3 - Alejandro MohamadCertificación Zend PHP 5.3 - Alejandro Mohamad
Certificación Zend PHP 5.3 - Alejandro Mohamad
 
Mule functional, blackbox, unit testing
Mule functional, blackbox, unit testingMule functional, blackbox, unit testing
Mule functional, blackbox, unit testing
 
Implementing Blackbox Testing
Implementing Blackbox TestingImplementing Blackbox Testing
Implementing Blackbox Testing
 
Blackbox
BlackboxBlackbox
Blackbox
 
Structural testing
Structural testingStructural testing
Structural testing
 
Control Flow Testing
Control Flow TestingControl Flow Testing
Control Flow Testing
 
Structural and functional testing
Structural and functional testingStructural and functional testing
Structural and functional testing
 
Basis path testing
Basis path testingBasis path testing
Basis path testing
 
01 software test engineering (manual testing)
01 software test engineering (manual testing)01 software test engineering (manual testing)
01 software test engineering (manual testing)
 
Chapter 8 software testing
Chapter 8 software testingChapter 8 software testing
Chapter 8 software testing
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Testing
TestingTesting
Testing
 
Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence Knowledge Representation in Artificial intelligence
Knowledge Representation in Artificial intelligence
 
Black & White Box testing
Black & White Box testingBlack & White Box testing
Black & White Box testing
 
Knowledge representation in AI
Knowledge representation in AIKnowledge representation in AI
Knowledge representation in AI
 

Similar to Code Complexity 101: Understanding Cyclomatic Complexity

Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Ziyauddin Shaik
 
Declare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsDeclare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsEelco Visser
 
Project 2Project 2.pdfIntroduction to Programming EECS 1.docx
Project 2Project 2.pdfIntroduction to Programming  EECS 1.docxProject 2Project 2.pdfIntroduction to Programming  EECS 1.docx
Project 2Project 2.pdfIntroduction to Programming EECS 1.docxwkyra78
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxAaliyanShaikh
 
Project Euler in Python
Project Euler in PythonProject Euler in Python
Project Euler in PythonTetsuo Koyama
 
Ch-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsCh-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsMAHERMOHAMED27
 
The Mathematics of RSA Encryption
The Mathematics of RSA EncryptionThe Mathematics of RSA Encryption
The Mathematics of RSA EncryptionNathan F. Dunn
 
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersSheila Sinclair
 
Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)
Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)
Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)Omkar Rane
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionEelco Visser
 
Elliptic curve scalar multiplier using karatsuba
Elliptic curve scalar multiplier using karatsubaElliptic curve scalar multiplier using karatsuba
Elliptic curve scalar multiplier using karatsubaIAEME Publication
 
Assignment2 – Simplified DES Encrypt and Decrypt .docx
Assignment2 – Simplified DES Encrypt and Decrypt                  .docxAssignment2 – Simplified DES Encrypt and Decrypt                  .docx
Assignment2 – Simplified DES Encrypt and Decrypt .docxmckellarhastings
 
Assignment2 – Simplified DES Encrypt and Decrypt .docx
Assignment2 – Simplified DES Encrypt and Decrypt                  .docxAssignment2 – Simplified DES Encrypt and Decrypt                  .docx
Assignment2 – Simplified DES Encrypt and Decrypt .docxedmondpburgess27164
 

Similar to Code Complexity 101: Understanding Cyclomatic Complexity (20)

Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 
Declare Your Language: Dynamic Semantics
Declare Your Language: Dynamic SemanticsDeclare Your Language: Dynamic Semantics
Declare Your Language: Dynamic Semantics
 
Project 2Project 2.pdfIntroduction to Programming EECS 1.docx
Project 2Project 2.pdfIntroduction to Programming  EECS 1.docxProject 2Project 2.pdfIntroduction to Programming  EECS 1.docx
Project 2Project 2.pdfIntroduction to Programming EECS 1.docx
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
Project Euler in Python
Project Euler in PythonProject Euler in Python
Project Euler in Python
 
Ch-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsCh-2 final exam documet compler design elements
Ch-2 final exam documet compler design elements
 
The Mathematics of RSA Encryption
The Mathematics of RSA EncryptionThe Mathematics of RSA Encryption
The Mathematics of RSA Encryption
 
Dynamic Semantics
Dynamic SemanticsDynamic Semantics
Dynamic Semantics
 
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
 
Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)
Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)
Digit Factorial Chains .(Euler Problem -74) (Matlab Programming Solution)
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Complexity analysis in Algorithms
Complexity analysis in AlgorithmsComplexity analysis in Algorithms
Complexity analysis in Algorithms
 
C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
 
Compiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax DefinitionCompiler Construction | Lecture 2 | Declarative Syntax Definition
Compiler Construction | Lecture 2 | Declarative Syntax Definition
 
Elliptic curve scalar multiplier using karatsuba
Elliptic curve scalar multiplier using karatsubaElliptic curve scalar multiplier using karatsuba
Elliptic curve scalar multiplier using karatsuba
 
L2EP_report
L2EP_reportL2EP_report
L2EP_report
 
Time and Space Complexity
Time and Space ComplexityTime and Space Complexity
Time and Space Complexity
 
Assignment2 – Simplified DES Encrypt and Decrypt .docx
Assignment2 – Simplified DES Encrypt and Decrypt                  .docxAssignment2 – Simplified DES Encrypt and Decrypt                  .docx
Assignment2 – Simplified DES Encrypt and Decrypt .docx
 
Assignment2 – Simplified DES Encrypt and Decrypt .docx
Assignment2 – Simplified DES Encrypt and Decrypt                  .docxAssignment2 – Simplified DES Encrypt and Decrypt                  .docx
Assignment2 – Simplified DES Encrypt and Decrypt .docx
 

Recently uploaded

XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
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.
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
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
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
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
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 

Recently uploaded (20)

XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
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
 
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)
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
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...
 
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
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
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
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
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...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 

Code Complexity 101: Understanding Cyclomatic Complexity

  • 1. Code Complexity 101 Arun Saha, Ph.D. arunksaha AT gmail DOT com (A pragmatic programmer and a software craftsman) https://www.linkedin.com/in/arunksaha
  • 2. Complexity Kills What November 2014 Code Complexity 101 2 Sphaghetti Junction
  • 3. (Bitter) Fact of life: Code complexity keeps increasing What November 2014 Code Complexity 101 3
  • 4. (Bitter) Fact of life: Code complexity keeps increasing What November 2014 Code Complexity 101 4 How to measure code complexity objectively?
  • 5. Simple Objective Metric: Cyclomatic Complexity What November 2014 Code Complexity 101 5 Developed by Thomas J. McCabe Sr. in 1976 Also known as McCabe Complexity Definition and Theory: http://en.wikipedia.org/wiki/Cyclomatic_complexity
  • 6. Cyclomatic Complexity of a Function, M = E – N + 1 Where, E = # of edges, N = # of nodes Details November 2014 Code Complexity 101 6 if (c1()) f1(); else f2(); if (c2()) f3(); else f4(); M = 9 – 7 + 1 = 3
  • 7. Informally, Complexity of a module*: sum of complexities of its functions * e.g. *.c, *.cc file November 2014 Code Complexity 101 7 What
  • 8. Complexity of a function: M = E – N + 1 How November 2014 Code Complexity 101 8 Lower bound: # of conditionals For example, in C and C++, each of the following keywords increase the complexity by 1 return, if, for, while, &&, ||, ?:, case, goto, break, continue
  • 9. FYI November 2014 Code Complexity 101 9 however, Calling function does not increase complexity of either the caller or the callee
  • 10. FYI November 2014 Code Complexity 101 10 however, Calling function does not increase complexity of either the caller or the callee
  • 11. Caveat November 2014 Code Complexity 101 11 McCabe Complexity != Big O Complexity They are totally completely different.
  • 12. Example 1 // Two functions of complexity 1 int c1_direct( int x ) { return x + 1; } int c1_redirect( int x ) { int const result = add( x, 1 ); return result; } E.g. November 2014 Code Complexity 101 12
  • 13. Example 2 // complexity: 2 // 1 for “return”, 1 for “?:” int c2_min( int x, int y ) { return y < x ? y : x; } E.g. November 2014 Code Complexity 101 13
  • 14. Example 3 // complexity: 3 // 1 for “if”, 1 for each “return” int c3_min( int x, int y ) { if( y < x ) { return y; } else { return x; } } E.g. November 2014 Code Complexity 101 14
  • 15. Example 4 // complexity: 3 // 1 for “return”, 1 for “&&”, 1 for “?:” int c4_bothtrue( int x, int y ) { return (x && y) ? 1 : 0; } E.g. November 2014 Code Complexity 101 15
  • 16. Same function can be (correctly) written with different complexities. FYI November 2014 Code Complexity 101 16
  • 17. Example 5.1 Problem BothNonZero: Given two int’s, return non-zero if both are non-zero, zero otherwise. // BothNonZero: Approach 1, Complexity: 4 int bothNonZero_1( int x, int y ) { if( x ) { if( y ) { return 1; } } return 0; } E.g. November 2014 Code Complexity 101 17
  • 18. Example 5.2 // BothNonZero: Approach 2, Complexity: 4 int bothNonZero_2( int x, int y ) { if( x && y ) { return 1; } return 0; } E.g. November 2014 Code Complexity 101 18
  • 19. Example 5.3 // BothNonZero: Approach 3, Complexity: 2 int bothNonZero_3( int x, int y ) { return x && y; } E.g. November 2014 Code Complexity 101 19
  • 20. FYI November 2014 Code Complexity 101 20 A common application is to compare the measured complexity against a set of threshold values. One such threshold set is as follows Cyclomatic Complexity Risk Evaluation 1 – 10 A simple program, without much risk 11 – 20 More complex, moderate risk 21 – 50 Complex, high risk program 51 + Unstable program (very high risk) Source: http://www.sei.cmu.edu/reports/97hb001.pdf p. 145 Fine, but how complex is really complex?
  • 21. Dev Team: Where should I prioritize my refactoring? Benefits November 2014 Code Complexity 101 21 QA Team: Where should I prioritize my testing?
  • 22. FYI November 2014 Code Complexity 101 22 I use CCCC http://sourceforge.net/projects/cccc/files/cccc/3.1.4/ with my simple wrapper mccabe.sh (available at) https://github.com/arunksaha/complexity (contains the function examples used here) Great, how can I get started today?
  • 23. November 2014 Code Complexity 101 23