SlideShare a Scribd company logo
CRAFTING CLEAN CODE
Ganesh Samarthyam
Coding Guidelines in CPP
“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
Ad

More Related Content

What's hot (7)

Sas array statement
Sas array statementSas array statement
Sas array statement
Ravi Mandal, MBA
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
pranav kumar verma
 
Sql Objects And PL/SQL
Sql Objects And PL/SQLSql Objects And PL/SQL
Sql Objects And PL/SQL
Gary Myers
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
Vamshi Santhapuri
 
Oracle - Program with PL/SQL - Lession 13
Oracle - Program with PL/SQL - Lession 13Oracle - Program with PL/SQL - Lession 13
Oracle - Program with PL/SQL - Lession 13
Thuan Nguyen
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 
structure,pointerandstring
structure,pointerandstringstructure,pointerandstring
structure,pointerandstring
baabtra.com - No. 1 supplier of quality freshers
 

Similar to Coding Guidelines in CPP (20)

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 database
Introduction to databaseIntroduction to database
Introduction to database
Pongsakorn U-chupala
 
C++ theory
C++ theoryC++ theory
C++ theory
Shyam Khant
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
application developer
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handling
Suite Solutions
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Templates2
Templates2Templates2
Templates2
zindadili
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
Syed Asrarali
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
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
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handling
Suite Solutions
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
Ad

More from CodeOps Technologies LLP (20)

AWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetupAWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetup
CodeOps Technologies LLP
 
Understanding azure batch service
Understanding azure batch serviceUnderstanding azure batch service
Understanding azure batch service
CodeOps Technologies LLP
 
DEVOPS AND MACHINE LEARNING
DEVOPS AND MACHINE LEARNINGDEVOPS AND MACHINE LEARNING
DEVOPS AND MACHINE LEARNING
CodeOps Technologies LLP
 
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONSSERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
CodeOps Technologies LLP
 
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONSBUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
CodeOps Technologies LLP
 
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICESAPPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
CodeOps Technologies LLP
 
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPSBUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
CodeOps Technologies LLP
 
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNERCREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CodeOps Technologies LLP
 
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CodeOps Technologies LLP
 
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESSWRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
CodeOps Technologies LLP
 
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh SharmaTraining And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
CodeOps Technologies LLP
 
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu SalujaDeploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
CodeOps Technologies LLP
 
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
CodeOps Technologies LLP
 
YAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra KhareYAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra Khare
CodeOps Technologies LLP
 
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
CodeOps Technologies LLP
 
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta JhaMonitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
CodeOps Technologies LLP
 
Jet brains space intro presentation
Jet brains space intro presentationJet brains space intro presentation
Jet brains space intro presentation
CodeOps Technologies LLP
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
 
Distributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps FoundationDistributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps Foundation
CodeOps Technologies LLP
 
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire  "Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
CodeOps Technologies LLP
 
AWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetupAWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetup
CodeOps Technologies LLP
 
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONSBUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
CodeOps Technologies LLP
 
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICESAPPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
CodeOps Technologies LLP
 
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPSBUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
CodeOps Technologies LLP
 
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNERCREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CodeOps Technologies LLP
 
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CodeOps Technologies LLP
 
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESSWRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
CodeOps Technologies LLP
 
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh SharmaTraining And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
CodeOps Technologies LLP
 
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu SalujaDeploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
CodeOps Technologies LLP
 
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
CodeOps Technologies LLP
 
YAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra KhareYAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra Khare
CodeOps Technologies LLP
 
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
CodeOps Technologies LLP
 
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta JhaMonitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
CodeOps Technologies LLP
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
CodeOps Technologies LLP
 
Distributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps FoundationDistributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps Foundation
CodeOps Technologies LLP
 
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire  "Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
CodeOps Technologies LLP
 
Ad

Recently uploaded (20)

How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 

Coding Guidelines in CPP

  • 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