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

Natural Language Query to SQL conversion using Machine Learning Approach
Natural Language Query to SQL conversion using Machine Learning ApproachNatural Language Query to SQL conversion using Machine Learning Approach
Natural Language Query to SQL conversion using Machine Learning ApproachMinhazul Arefin
 
Model Based Software Architectures
Model Based Software ArchitecturesModel Based Software Architectures
Model Based Software ArchitecturesMunazza-Mah-Jabeen
 
Evolving role of Software,Legacy software,CASE tools,Process Models,CMMI
Evolving role of Software,Legacy software,CASE tools,Process Models,CMMIEvolving role of Software,Legacy software,CASE tools,Process Models,CMMI
Evolving role of Software,Legacy software,CASE tools,Process Models,CMMInimmik4u
 
Software Development Methodologies-HSM, SSADM
Software Development Methodologies-HSM, SSADMSoftware Development Methodologies-HSM, SSADM
Software Development Methodologies-HSM, SSADMNana Sarpong
 
Fault tolearant system
Fault tolearant systemFault tolearant system
Fault tolearant systemarvinthsaran
 
Improving software economics
Improving software economicsImproving software economics
Improving software economicsdeep sharma
 
Software Project Estimation
Software Project EstimationSoftware Project Estimation
Software Project EstimationFrank Vogelezang
 
Pattern recognition and Machine Learning.
Pattern recognition and Machine Learning.Pattern recognition and Machine Learning.
Pattern recognition and Machine Learning.Rohit Kumar
 
Non Functional Requirement.
Non Functional Requirement.Non Functional Requirement.
Non Functional Requirement.Khushboo Shaukat
 
Project control and process instrumentation
Project control and process instrumentationProject control and process instrumentation
Project control and process instrumentationKuppusamy P
 
Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19koolkampus
 

What's hot (20)

Natural Language Query to SQL conversion using Machine Learning Approach
Natural Language Query to SQL conversion using Machine Learning ApproachNatural Language Query to SQL conversion using Machine Learning Approach
Natural Language Query to SQL conversion using Machine Learning Approach
 
The Software Development Process
The Software Development ProcessThe Software Development Process
The Software Development Process
 
Model Based Software Architectures
Model Based Software ArchitecturesModel Based Software Architectures
Model Based Software Architectures
 
Evolving role of Software,Legacy software,CASE tools,Process Models,CMMI
Evolving role of Software,Legacy software,CASE tools,Process Models,CMMIEvolving role of Software,Legacy software,CASE tools,Process Models,CMMI
Evolving role of Software,Legacy software,CASE tools,Process Models,CMMI
 
Software Development Methodologies-HSM, SSADM
Software Development Methodologies-HSM, SSADMSoftware Development Methodologies-HSM, SSADM
Software Development Methodologies-HSM, SSADM
 
Stm unit1
Stm unit1Stm unit1
Stm unit1
 
What is the psychology of testing
What is the psychology of testingWhat is the psychology of testing
What is the psychology of testing
 
Ooad
OoadOoad
Ooad
 
Fault tolearant system
Fault tolearant systemFault tolearant system
Fault tolearant system
 
Improving software economics
Improving software economicsImproving software economics
Improving software economics
 
Software Project Estimation
Software Project EstimationSoftware Project Estimation
Software Project Estimation
 
Pattern recognition and Machine Learning.
Pattern recognition and Machine Learning.Pattern recognition and Machine Learning.
Pattern recognition and Machine Learning.
 
Input devices
Input devicesInput devices
Input devices
 
Autobahn primer
Autobahn primerAutobahn primer
Autobahn primer
 
Non Functional Requirement.
Non Functional Requirement.Non Functional Requirement.
Non Functional Requirement.
 
NLP
NLPNLP
NLP
 
Project control and process instrumentation
Project control and process instrumentationProject control and process instrumentation
Project control and process instrumentation
 
Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19Verification and Validation in Software Engineering SE19
Verification and Validation in Software Engineering SE19
 
Interaction styles
Interaction stylesInteraction styles
Interaction styles
 
Software complexity
Software complexitySoftware complexity
Software complexity
 

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

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 (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

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
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
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
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.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Recently uploaded (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
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 ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

Code Complexity 101

  • 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