SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 beyondMario Fusco
 
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 wheeltcurdt
 
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 modelingMario Fusco
 
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# 7Paulo Morgado
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
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 Ganesh Samarthyam
 
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 ProgrammerMario Fusco
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonSiddhi
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
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 codeGeshan Manandhar
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 

Was ist angesagt? (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
 

Ähnlich wie CRAFTING CLEAN CODE WITH C++ BEST PRACTICES

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 JavaJevgeni Kabanov
 
Data structures and algorithms lab1
Data structures and algorithms lab1Data structures and algorithms lab1
Data structures and algorithms lab1Bianca Teşilă
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpg_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpRaga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpSatish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpsinghadarsh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharpMody Farouk
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handlingSuite Solutions
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14Syed Asrarali
 

Ähnlich wie CRAFTING CLEAN CODE WITH C++ BEST PRACTICES (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
Intro to tsqlIntro to tsql
Intro to tsql
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
 

Mehr von Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
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”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
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)Ganesh Samarthyam
 
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++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
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 LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
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 quizGanesh Samarthyam
 
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...Ganesh Samarthyam
 
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...Ganesh Samarthyam
 
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 2016Ganesh Samarthyam
 

Mehr von 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
 

Kürzlich hochgeladen

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 

Kürzlich hochgeladen (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 

CRAFTING CLEAN CODE WITH C++ BEST PRACTICES

  • 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