SlideShare a Scribd company logo
1 of 27
Download to read offline
CRAFTING CLEAN CODE
Ganesh Samarthyam
“Keeping “clean” is a habit - it’s not to
do with “skills” or “ability”!
WARM-UP EXERCISE
ASSUME MANY PLACES YOU HAVE SUCH CODE- HOW TO IMPROVE?
#include <vector>
#include <iostream>
using namespace std;
bool validate_temperature_measures(vector<int> &measures) {
for(vector<int>::iterator i = measures.begin(); i != measures.end(); ++i ) {
if( *i < 0 || *i > 100) {
return false;
}
}
return true;
}
int main() {
vector<int> measures = { 23, 66, 25, 85, 110, 45, 34, 90 };
cout << "valid measures? "
<< std::boolalpha << validate_temperature_measures(measures) << endl;
}
ATTEMPT #1
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
template<typename T>
class is_outside_range : public unary_function<T, bool> {
public:
is_outside_range(const T& low, const T& high) : low_(low), high_(high) {}
bool operator()( const T& val ) const {return val < low_ || val > high_; }
private:
T low_, high_;
};
bool validate_temperature_measures(vector<int> &measures) {
vector<int>::iterator result = find_if(measures.begin(), measures.end(),
is_outside_range<int>(0, 100));
return result == measures.end();
}
int main() {
vector<int> measures = { 23, 66, 25, 85, 10, 45, 34, 90 };
cout << "valid measures? " << std::boolalpha <<
validate_temperature_measures(measures) << endl;
}
ATTEMPT #2
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
using namespace std;
bool validate_temperature_measures(vector<int> &measures) {
function<bool(int)> temperature_validator =
[](const int value) {
const int low = 0;
const int high = 100;
return (value < low) || (value > high);
};
vector<int>::iterator result = find_if(measures.begin(), measures.end(),
temperature_validator);
return result == measures.end();
}
int main() {
vector<int> measures = { 23, 66, 25, 85, 10, 45, 34, 90 };
cout << "valid measures? " << std::boolalpha <<
validate_temperature_measures(measures) << endl;
}
GETTING STARTED
ESSENTIALS
➤ Ensure traceability within code
➤ Do not write “sloppy code”
➤ Provide necessary copyright notice, change logs, etc. in each
source and header files
FORMATTING
➤ “Consistency” is key to formatting
➤ Example: placement of curly braces - “{“ and “}”
➤ Another obvious example: tabs vs. whitespaces
➤ Keep lines within 80 characters
➤ Ensure “density” is not too high
➤ E.g., leave out enough a linespace between group of
statements
➤ Have an ordering of member functions, data members, etc.
➤ Ensure proper intendation
MEANINGFUL NAMES
➤ Use intention-revealing names
int d; // elapsed time in days
int elapsedTimeInDays;
➤ Use searchable names
for(int j = 0; j < 34; j++)
s+= (t(j)*4)/5;
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for(int task; task < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[task] * realDaysPerIdealDay;
int realTaskWeeks = (realDays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
Clean Code: A Handbook of Agile Software Craftsmanship, Robert C. Martin, Prentice Hall, 2008
NAMING
➤ Avoid Hungarian notation and member prefixes
➤ Class names should have noun or noun phrases (and not be a
verb)
➤ Method names should have verb or verb phrase names
➤ Avoid typos and smelling mistakes in the code
COMMENTS
➤ Provide good “internal documentation”
➤ Comments do not make up for bad code
➤ Explain yourself in code
➤ Explain intent
➤ Avoid commenting-out code
➤ Avoid redundant comments
➤ Provide mandated comments
➤ Use position markers sparingly (e.g., // Actions ////////)
Clean Code: A Handbook of Agile Software Craftsmanship, Robert C. Martin, Prentice Hall, 2008
FUNCTIONS / METHODS
➤ Avoid macros - use inline functions instead
➤ Method names - neither too long, nor too short
➤ Keep parameter list small (not more than 4 or so parameters)
➤ Avoid “out” parameters - prefer return values instead
➤ Avoid friend functions
➤ Prefer const methods
➤ Ensure proper return from all paths
➤ Strive for exception safety
FUNCTIONS / METHODS
➤ Keep nesting level of functions low (not more than 3 or 4
levels deep)
➤ Keep Cyclomatic complexity low (less than 10 per method)
➤ Keep lines size small (more than 10 or so becomes difficult to
grasp)
➤ Avoid functions doing many things - do one thing (e.g.,
realloc does too many things)
➤ Avoid “stateful-functions” (e.g., strtok)
CLASSES
➤ Prefer one class per file
➤ Limit the number of members in a class
➤ Avoid public data members
➤ Limit the accessibility of the class members
➤ Have a ordering for the methods and data members; order
public, private, and protected members
➤ Keep the complexity of classes low - i.e., Weighted Methods
per Class (WMC) keep it low like 25 or 30
➤ Avoid “struct-like” classes
HARDCODING
➤ Avoid “hard-coded logic”
➤ Avoid “magic numbers”
➤ Avoid “magic strings”
“Adopt a coding standard and adhere
to it (as a team!)
“Code without unit tests is legacy
code!
CODING GUIDELINES
MISRA C/C++
https://www.misra-cpp.com/MISRACHome/tabid/128/Default.aspx
CERT C++
https://www.cert.org/downloads/secure-coding/assets/sei-cert-cpp-coding-standard-2016-v01.pdf
JSF++
http://www.stroustrup.com/JSF-AV-rules.pdf
Designed by Lockheed Martin for Joint Strike Fighter - Air Vehicle coding standard for C++
HIGH-INTEGRITY C++ CODING STANDARD
http://www.codingstandard.com/section/index/
GOOGLE C++ STYLE GUIDE
https://google.github.io/styleguide/cppguide.html
C++ CORE GUIDELINES
http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
ganesh@codeops.tech @GSamarthyam
www.codeops.tech slideshare.net/sgganesh
+91 98801 64463 bit.ly/sgganesh

More Related Content

What's hot

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 

What's hot (20)

FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
C# 7
C# 7C# 7
C# 7
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 

Similar to Coding Guidelines - Crafting Clean Code

Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
Jevgeni Kabanov
 
Data structures and algorithms lab1
Data structures and algorithms lab1Data structures and algorithms lab1
Data structures and algorithms lab1
Bianca Teşilă
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handling
Suite Solutions
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 

Similar to Coding Guidelines - Crafting Clean Code (20)

What's in a name
What's in a nameWhat's in a name
What's in a name
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
Data structures and algorithms lab1
Data structures and algorithms lab1Data structures and algorithms lab1
Data structures and algorithms lab1
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
C++ theory
C++ theoryC++ theory
C++ theory
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handling
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Templates2
Templates2Templates2
Templates2
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
 

More from Ganesh Samarthyam

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 
Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...
 
Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...
 
Refactoring for Software Design Smells - XP Conference - August 20th 2016
Refactoring for Software Design Smells - XP Conference - August 20th 2016Refactoring for Software Design Smells - XP Conference - August 20th 2016
Refactoring for Software Design Smells - XP Conference - August 20th 2016
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

Recently uploaded (20)

BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 

Coding Guidelines - Crafting Clean Code

  • 2.
  • 3. “Keeping “clean” is a habit - it’s not to do with “skills” or “ability”!
  • 5. ASSUME MANY PLACES YOU HAVE SUCH CODE- HOW TO IMPROVE? #include <vector> #include <iostream> using namespace std; bool validate_temperature_measures(vector<int> &measures) { for(vector<int>::iterator i = measures.begin(); i != measures.end(); ++i ) { if( *i < 0 || *i > 100) { return false; } } return true; } int main() { vector<int> measures = { 23, 66, 25, 85, 110, 45, 34, 90 }; cout << "valid measures? " << std::boolalpha << validate_temperature_measures(measures) << endl; }
  • 6. ATTEMPT #1 #include <vector> #include <algorithm> #include <iostream> using namespace std; template<typename T> class is_outside_range : public unary_function<T, bool> { public: is_outside_range(const T& low, const T& high) : low_(low), high_(high) {} bool operator()( const T& val ) const {return val < low_ || val > high_; } private: T low_, high_; }; bool validate_temperature_measures(vector<int> &measures) { vector<int>::iterator result = find_if(measures.begin(), measures.end(), is_outside_range<int>(0, 100)); return result == measures.end(); } int main() { vector<int> measures = { 23, 66, 25, 85, 10, 45, 34, 90 }; cout << "valid measures? " << std::boolalpha << validate_temperature_measures(measures) << endl; }
  • 7. ATTEMPT #2 #include <vector> #include <algorithm> #include <functional> #include <iostream> using namespace std; bool validate_temperature_measures(vector<int> &measures) { function<bool(int)> temperature_validator = [](const int value) { const int low = 0; const int high = 100; return (value < low) || (value > high); }; vector<int>::iterator result = find_if(measures.begin(), measures.end(), temperature_validator); return result == measures.end(); } int main() { vector<int> measures = { 23, 66, 25, 85, 10, 45, 34, 90 }; cout << "valid measures? " << std::boolalpha << validate_temperature_measures(measures) << endl; }
  • 9. ESSENTIALS ➤ Ensure traceability within code ➤ Do not write “sloppy code” ➤ Provide necessary copyright notice, change logs, etc. in each source and header files
  • 10. FORMATTING ➤ “Consistency” is key to formatting ➤ Example: placement of curly braces - “{“ and “}” ➤ Another obvious example: tabs vs. whitespaces ➤ Keep lines within 80 characters ➤ Ensure “density” is not too high ➤ E.g., leave out enough a linespace between group of statements ➤ Have an ordering of member functions, data members, etc. ➤ Ensure proper intendation
  • 11. MEANINGFUL NAMES ➤ Use intention-revealing names int d; // elapsed time in days int elapsedTimeInDays; ➤ Use searchable names for(int j = 0; j < 34; j++) s+= (t(j)*4)/5; int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; int sum = 0; for(int task; task < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[task] * realDaysPerIdealDay; int realTaskWeeks = (realDays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; } Clean Code: A Handbook of Agile Software Craftsmanship, Robert C. Martin, Prentice Hall, 2008
  • 12. NAMING ➤ Avoid Hungarian notation and member prefixes ➤ Class names should have noun or noun phrases (and not be a verb) ➤ Method names should have verb or verb phrase names ➤ Avoid typos and smelling mistakes in the code
  • 13. COMMENTS ➤ Provide good “internal documentation” ➤ Comments do not make up for bad code ➤ Explain yourself in code ➤ Explain intent ➤ Avoid commenting-out code ➤ Avoid redundant comments ➤ Provide mandated comments ➤ Use position markers sparingly (e.g., // Actions ////////) Clean Code: A Handbook of Agile Software Craftsmanship, Robert C. Martin, Prentice Hall, 2008
  • 14. FUNCTIONS / METHODS ➤ Avoid macros - use inline functions instead ➤ Method names - neither too long, nor too short ➤ Keep parameter list small (not more than 4 or so parameters) ➤ Avoid “out” parameters - prefer return values instead ➤ Avoid friend functions ➤ Prefer const methods ➤ Ensure proper return from all paths ➤ Strive for exception safety
  • 15. FUNCTIONS / METHODS ➤ Keep nesting level of functions low (not more than 3 or 4 levels deep) ➤ Keep Cyclomatic complexity low (less than 10 per method) ➤ Keep lines size small (more than 10 or so becomes difficult to grasp) ➤ Avoid functions doing many things - do one thing (e.g., realloc does too many things) ➤ Avoid “stateful-functions” (e.g., strtok)
  • 16. CLASSES ➤ Prefer one class per file ➤ Limit the number of members in a class ➤ Avoid public data members ➤ Limit the accessibility of the class members ➤ Have a ordering for the methods and data members; order public, private, and protected members ➤ Keep the complexity of classes low - i.e., Weighted Methods per Class (WMC) keep it low like 25 or 30 ➤ Avoid “struct-like” classes
  • 17. HARDCODING ➤ Avoid “hard-coded logic” ➤ Avoid “magic numbers” ➤ Avoid “magic strings”
  • 18. “Adopt a coding standard and adhere to it (as a team!)
  • 19. “Code without unit tests is legacy code!
  • 23. JSF++ http://www.stroustrup.com/JSF-AV-rules.pdf Designed by Lockheed Martin for Joint Strike Fighter - Air Vehicle coding standard for C++
  • 24. HIGH-INTEGRITY C++ CODING STANDARD http://www.codingstandard.com/section/index/
  • 25. GOOGLE C++ STYLE GUIDE https://google.github.io/styleguide/cppguide.html