SlideShare a Scribd company logo
Clean Code
by Sazzad Abdul Hasib
Two Reasons
1. You are a programmer
2. You want to be a better programmer
Elegance
“ I like my code to be elegant and efficient. Clean
code does one thing well”
---- Bjarne Stroustrup
The only valid measurement of code
quality: WTF/minute
code
review
WTF
WTF is this!
WTF
Use Intention-Revealing Names
public List<int[]> getThem() {
List<int[]> list1 = new ArrayList<int[]>();
for (int[] x : theList)
if (x[0] == 4)
list1.add(x);
return list1;
}
Meaningful Names
Use Intention-Revealing Names
public List<Cell> getFlaggedCells() {
List<Cell> flaggedCells = new ArrayList<Cell>();
for (Cell cell : gameBoard)
if (cell.isFlagged())
flaggedCells.add(cell);
return flaggedCells;
}
Meaningful Names
Avoid Disinformation
int a = l;
if (0 == l)
a = 01;
else
l = 01;
Meaningful Names
Make Meaningful Distinctions
public static void copyChars(char a1[], char a2[])
{
for (int i = 0; i < a1.length; i++)
{
a2[i] = a1[i];
}
}
Meaningful Names
Use Pronounceable Names
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/* ... */
};
Meaningful Names
Meaningful Names
Use Pronounceable Names
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;;
private final String recordId = "102";
/* ... */
};
Meaningful Names
Use Searchable Names
for (int j = 0; j < 34; j++) {
s += (t[j] * 4) / 5;
}
Meaningful Names
Use Searchable Names
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j = 0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] *realDaysPerIdealDay;
int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
Meaningful Names
Use Searchable Names
PhoneNumber phoneString;
PhoneNumber phone;
String NameString;
String Name;
Meaningful Names
Avoid Mental Mapping
for (a = 0; a < 10; a++)
for (b = 0; b < 10; b++)
Class Names
Manager, Processor, Data, Info
Meaningful Names
Avoid Mental Mapping
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
Class Names
// Classes and objects should have noun or noun phrase names
Customer, WikiPage, Account, AddressParser
// a class name should not be a verb
Meaningful Names
Method Names
postPayment, deletePage, save
// methods should have verb or verb phrase names
// can be prefixed with get , set , is
string name = employee.getName();
customer.setName("mike");
if (paycheck.isPosted())...
Meaningful Names
Don’t be Cute
Cuteness in code often appears in the form of colloquialisms or slang.
For example,
Don’t use the name whack() to mean kill() .
Don’t tell little culture dependent jokes like eatMyShorts() to mean abort().
Meaningful Names
Pick One Word per Concept
fetch, retrieve, get // as equivalent methods
controller, manager, driver // confusing
Don’t Pun
// avoid using the same word for two purposes
// insert, add
Meaningful Names
Use Solution Domain Names
//AccountVisitor, JobQueue
// people who read your code will be programmers
//use computer science (CS) terms, algorithm names, pattern names, math
terms, and so forth.
Add Meaningful Context
firstName, lastName, street, city, state, zipcode // a better solution
addrFirstName, addrLastName, addrState // a far better solution
Meaningful Names
Don’t Add Gratuitous Context
-> Class Address
Address // is a fine name for a class
AccountAddress, CustomerAddress
// are fine names for instances of the class Address but could be poor
names for classes
// In an imaginary application called “Gas Station Deluxe,” it is a bad idea to
prefix every class with GSD .
Functions
Rules of Functions
// 1. should be small
// 2. should be smaller than that
// < 150 characters per line
// < 20 lines
Do One Thing
// FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL.
// THEY SHOULD DO IT ONLY.
Functions
One Level of Abstraction per Function
public void doTheDomesticThings() {
takeOutTheTrash();
walkTheDog();
for (Dish dish : dirtyDishStack) {
sink.washDish(dish);
teaTowel.dryDish(dish);
}
}
Functions
One Level of Abstraction per Function
public void doTheDomesticThings() {
takeOutTheTrash();
walkTheDog();
doTheDishes();
}
Functions
Single Responsibility Principle
In object-oriented programming, the single responsibility principle
states that every class should have responsibility over a single part of
the functionality provided by the software, and that responsibility
should be entirely encapsulated by the class. All its services should be
narrowly aligned with that responsibility.
Source: WIKI
Functions
Open / Closed Principle
In object-oriented programming, the open/closed principle states
“software entities (classes, modules, functions, etc.) should be open for
extension, but closed for modification”.
Source : WIKI
Functions
Use Descriptive Names
// isModified or includeSetupAndTeardownPages
Function Arguments
// the ideal number of arguments for a function is zero
Functions
Common Monadic Forms
// if a function is going to transform its input argument, the
transformation should appear as the return value
StringBuffer transform(StringBuffer in)
// is better than
void transform(StringBuffer out)
Functions
Common Monadic Forms
// asking a question about that argument
boolean fileExists(“MyFile”)
// operating on that argument, transforming and returning it
InputStream fileOpen(“MyFile”)
// event, use the argument to alter the state of the system
void passwordAttemptFailedNtimes(int attempts)
Functions
Dyadic Functions
writeField(name)
// is easier to understand than
writeField(outputStream, name)
// perfectly reasonable
Point p = new Point(0,0)
// problematic
assertEquals(expected, actual)
Functions
Argument Objects
Circle makeCircle(double x, double y, double radius);
Circle makeCircle(Point center, double radius);
Don’t Repeat Yourself (DRY)
// duplication may be the root of all evil in software
Functions
Structured Programming
// Edsger Dijkstra’s rules
// one entry
// one exit
// functions small
// occasional multiple return, break, or continue statement
Comments
Comments Do Not Make Up for Bad Code
// don’t comment bad code, rewrite it!
Explain Yourself in Code
// Check to see if the employee is eligible for full
benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
if (employee.isEligibleForFullBenefits())
Comments (Good)
Legal Comments
// Copyright (C) 2011 by Osoco. All rights reserved.
Clarification
assertTrue(a.compareTo(b) == -1); // a < b
assertTrue(b.compareTo(a) == 1); // b > a
Comments (Good)
Warning of Consequences
/SimpleDateFormat is not thread safe,
//so we need to create each instance independently.
SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy");
TODO Comments
Comments (Good)
Amplification
String listItemContent = match.group(3).trim();
// the trim is real important. It removes the starting
// spaces that could cause the item to be recognized
// as another list.
new ListItemWidget(this, listItemContent, this.level + 1);
return buildList(text.substring(match.end()));
Comments (Bad)
Redundant Comments / Noise Comments
/**
* The processor delay for this component.
*/
protected int backgroundProcessorDelay = -1;
/**
* The lifecycle event support for this component.
*/
protected LifecycleSupport lifecycle =
new LifecycleSupport(this);
Comments (Bad)
Journal Comments
Changes (from 11-Oct-2001)
--------------------------
11-Oct-2001 : Re-organised the class and moved it to new
package com.jrefinery.date (DG);
05-Nov-2001 : Added a getDescription() method, and
eliminated NotableDate class (DG);
Comments (Bad)
- Don’t Use a Comment When You Can Use a Function
or a Variable
- Commented-Out Code
- Attributions and Bylines (added by Sazzad)
- HTML Comments
Formatting
Vertical Distance
// variables
// should be declared as close to their usage as possible
// instance variables
// should be declared at the top of the class
// dependent functions
// if one function calls another, they should be vertically
// close, and the caller should be above the called
// conceptual affinity
// certain bits of code want to be near other bit
Formatting
Team Rules
// every programmer has his own favorite formatting rules
// but if he works in a team
// then the team rules
Any Question !!!

More Related Content

What's hot

Cours08 exceptions
Cours08 exceptionsCours08 exceptions
Cours08 exceptionsIssam Talkam
 
Chapitre 4 Java script
Chapitre 4 Java scriptChapitre 4 Java script
Chapitre 4 Java script
Manel Ben Sassi
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Thomas Zimmermann
 
Improving notes addressing experience with recent contacts
Improving notes addressing experience with recent contactsImproving notes addressing experience with recent contacts
Improving notes addressing experience with recent contacts
Vinayak Tavargeri
 
Cours php
Cours php Cours php
Cours php
Yassine Badri
 
08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우
jaypi Ko
 
Using the new IBM ODBC Driver for Notes/Domino 9.0
Using the new IBM ODBC Driver for Notes/Domino 9.0Using the new IBM ODBC Driver for Notes/Domino 9.0
Using the new IBM ODBC Driver for Notes/Domino 9.0
Mat Newman
 
10 컨트롤윈도우
10 컨트롤윈도우10 컨트롤윈도우
10 컨트롤윈도우
jaypi Ko
 
Clean code
Clean codeClean code
Langage C#
Langage C#Langage C#
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기Heo Seungwook
 
Architectural caching patterns for kubernetes
Architectural caching patterns for kubernetesArchitectural caching patterns for kubernetes
Architectural caching patterns for kubernetes
Rafał Leszko
 
HCL Notes and Nomad Troubleshooting for Dummies
HCL Notes and Nomad Troubleshooting for DummiesHCL Notes and Nomad Troubleshooting for Dummies
HCL Notes and Nomad Troubleshooting for Dummies
panagenda
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
How to Bring HCL Nomad Web and Domino Together Without SafeLinx
How to Bring HCL Nomad Web and Domino Together Without SafeLinxHow to Bring HCL Nomad Web and Domino Together Without SafeLinx
How to Bring HCL Nomad Web and Domino Together Without SafeLinx
panagenda
 
Correction de td poo n2
Correction de td poo n2Correction de td poo n2
Correction de td poo n2yassine kchiri
 
Rapport Sockets en Java
Rapport Sockets en JavaRapport Sockets en Java
Rapport Sockets en Java
Soukaina Boujadi
 
Formation HTML pour Bac Informatique
Formation HTML pour Bac InformatiqueFormation HTML pour Bac Informatique
Formation HTML pour Bac Informatique
Mohamed Anas Ben Othman
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio
 

What's hot (20)

Cours08 exceptions
Cours08 exceptionsCours08 exceptions
Cours08 exceptions
 
Chapitre 4 Java script
Chapitre 4 Java scriptChapitre 4 Java script
Chapitre 4 Java script
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Improving notes addressing experience with recent contacts
Improving notes addressing experience with recent contactsImproving notes addressing experience with recent contacts
Improving notes addressing experience with recent contacts
 
Cours php
Cours php Cours php
Cours php
 
08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우08 부모윈도우 자식윈도우
08 부모윈도우 자식윈도우
 
Using the new IBM ODBC Driver for Notes/Domino 9.0
Using the new IBM ODBC Driver for Notes/Domino 9.0Using the new IBM ODBC Driver for Notes/Domino 9.0
Using the new IBM ODBC Driver for Notes/Domino 9.0
 
10 컨트롤윈도우
10 컨트롤윈도우10 컨트롤윈도우
10 컨트롤윈도우
 
Clean code
Clean codeClean code
Clean code
 
Langage C#
Langage C#Langage C#
Langage C#
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기C++ 프로젝트에 단위 테스트 도입하기
C++ 프로젝트에 단위 테스트 도입하기
 
Architectural caching patterns for kubernetes
Architectural caching patterns for kubernetesArchitectural caching patterns for kubernetes
Architectural caching patterns for kubernetes
 
HCL Notes and Nomad Troubleshooting for Dummies
HCL Notes and Nomad Troubleshooting for DummiesHCL Notes and Nomad Troubleshooting for Dummies
HCL Notes and Nomad Troubleshooting for Dummies
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
How to Bring HCL Nomad Web and Domino Together Without SafeLinx
How to Bring HCL Nomad Web and Domino Together Without SafeLinxHow to Bring HCL Nomad Web and Domino Together Without SafeLinx
How to Bring HCL Nomad Web and Domino Together Without SafeLinx
 
Correction de td poo n2
Correction de td poo n2Correction de td poo n2
Correction de td poo n2
 
Rapport Sockets en Java
Rapport Sockets en JavaRapport Sockets en Java
Rapport Sockets en Java
 
Formation HTML pour Bac Informatique
Formation HTML pour Bac InformatiqueFormation HTML pour Bac Informatique
Formation HTML pour Bac Informatique
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 

Similar to Clean Code

SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
ARORACOCKERY2111
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
Maarten Balliauw
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
Tara Hardin
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
Intelligo Technologies
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
Ólafur Andri Ragnarsson
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
IBM
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
Jagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 

Similar to Clean Code (20)

Clean code
Clean codeClean code
Clean code
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 

More from Nascenia IT

AI Tools for Productivity: Exploring Prompt Engineering and Key Features
AI Tools for Productivity: Exploring Prompt Engineering and Key FeaturesAI Tools for Productivity: Exploring Prompt Engineering and Key Features
AI Tools for Productivity: Exploring Prompt Engineering and Key Features
Nascenia IT
 
Introduction to basic data analytics tools
Introduction to basic data analytics toolsIntroduction to basic data analytics tools
Introduction to basic data analytics tools
Nascenia IT
 
Communication workshop in nascenia
Communication workshop in nasceniaCommunication workshop in nascenia
Communication workshop in nascenia
Nascenia IT
 
The Art of Statistical Deception
The Art of Statistical DeceptionThe Art of Statistical Deception
The Art of Statistical Deception
Nascenia IT
 
করোনায় কী করি!
করোনায় কী করি!করোনায় কী করি!
করোনায় কী করি!
Nascenia IT
 
GDPR compliance expectations from the development team
GDPR compliance expectations from the development teamGDPR compliance expectations from the development team
GDPR compliance expectations from the development team
Nascenia IT
 
Writing Clean Code
Writing Clean CodeWriting Clean Code
Writing Clean Code
Nascenia IT
 
History & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer VisionHistory & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer Vision
Nascenia IT
 
Ruby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineRuby on Rails: Coding Guideline
Ruby on Rails: Coding Guideline
Nascenia IT
 
iphone 11 new features
iphone 11 new featuresiphone 11 new features
iphone 11 new features
Nascenia IT
 
Software quality assurance and cyber security
Software quality assurance and cyber securitySoftware quality assurance and cyber security
Software quality assurance and cyber security
Nascenia IT
 
Job Market Scenario For Freshers
Job Market Scenario For Freshers Job Market Scenario For Freshers
Job Market Scenario For Freshers
Nascenia IT
 
Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)
Nascenia IT
 
CSS for Developers
CSS for DevelopersCSS for Developers
CSS for Developers
Nascenia IT
 
Big commerce app development
Big commerce app developmentBig commerce app development
Big commerce app development
Nascenia IT
 
Integrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails ApplicationIntegrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails Application
Nascenia IT
 
Shopify
ShopifyShopify
Shopify
Nascenia IT
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
Nascenia IT
 
Clean code
Clean codeClean code
Clean code
Nascenia IT
 
Ruby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 AppsRuby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 Apps
Nascenia IT
 

More from Nascenia IT (20)

AI Tools for Productivity: Exploring Prompt Engineering and Key Features
AI Tools for Productivity: Exploring Prompt Engineering and Key FeaturesAI Tools for Productivity: Exploring Prompt Engineering and Key Features
AI Tools for Productivity: Exploring Prompt Engineering and Key Features
 
Introduction to basic data analytics tools
Introduction to basic data analytics toolsIntroduction to basic data analytics tools
Introduction to basic data analytics tools
 
Communication workshop in nascenia
Communication workshop in nasceniaCommunication workshop in nascenia
Communication workshop in nascenia
 
The Art of Statistical Deception
The Art of Statistical DeceptionThe Art of Statistical Deception
The Art of Statistical Deception
 
করোনায় কী করি!
করোনায় কী করি!করোনায় কী করি!
করোনায় কী করি!
 
GDPR compliance expectations from the development team
GDPR compliance expectations from the development teamGDPR compliance expectations from the development team
GDPR compliance expectations from the development team
 
Writing Clean Code
Writing Clean CodeWriting Clean Code
Writing Clean Code
 
History & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer VisionHistory & Introduction of Neural Network and use of it in Computer Vision
History & Introduction of Neural Network and use of it in Computer Vision
 
Ruby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineRuby on Rails: Coding Guideline
Ruby on Rails: Coding Guideline
 
iphone 11 new features
iphone 11 new featuresiphone 11 new features
iphone 11 new features
 
Software quality assurance and cyber security
Software quality assurance and cyber securitySoftware quality assurance and cyber security
Software quality assurance and cyber security
 
Job Market Scenario For Freshers
Job Market Scenario For Freshers Job Market Scenario For Freshers
Job Market Scenario For Freshers
 
Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)Modern Frontend Technologies (BEM, Retina)
Modern Frontend Technologies (BEM, Retina)
 
CSS for Developers
CSS for DevelopersCSS for Developers
CSS for Developers
 
Big commerce app development
Big commerce app developmentBig commerce app development
Big commerce app development
 
Integrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails ApplicationIntegrating QuickBooks Desktop with Rails Application
Integrating QuickBooks Desktop with Rails Application
 
Shopify
ShopifyShopify
Shopify
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
Clean code
Clean codeClean code
Clean code
 
Ruby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 AppsRuby conf 2016 - Secrets of Testing Rails 5 Apps
Ruby conf 2016 - Secrets of Testing Rails 5 Apps
 

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 

Clean Code

  • 1. Clean Code by Sazzad Abdul Hasib
  • 2. Two Reasons 1. You are a programmer 2. You want to be a better programmer
  • 3. Elegance “ I like my code to be elegant and efficient. Clean code does one thing well” ---- Bjarne Stroustrup
  • 4. The only valid measurement of code quality: WTF/minute code review WTF WTF is this! WTF
  • 5. Use Intention-Revealing Names public List<int[]> getThem() { List<int[]> list1 = new ArrayList<int[]>(); for (int[] x : theList) if (x[0] == 4) list1.add(x); return list1; } Meaningful Names
  • 6. Use Intention-Revealing Names public List<Cell> getFlaggedCells() { List<Cell> flaggedCells = new ArrayList<Cell>(); for (Cell cell : gameBoard) if (cell.isFlagged()) flaggedCells.add(cell); return flaggedCells; } Meaningful Names
  • 7. Avoid Disinformation int a = l; if (0 == l) a = 01; else l = 01; Meaningful Names
  • 8. Make Meaningful Distinctions public static void copyChars(char a1[], char a2[]) { for (int i = 0; i < a1.length; i++) { a2[i] = a1[i]; } } Meaningful Names
  • 9. Use Pronounceable Names class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /* ... */ }; Meaningful Names
  • 10. Meaningful Names Use Pronounceable Names class Customer { private Date generationTimestamp; private Date modificationTimestamp;; private final String recordId = "102"; /* ... */ };
  • 11. Meaningful Names Use Searchable Names for (int j = 0; j < 34; j++) { s += (t[j] * 4) / 5; }
  • 12. Meaningful Names Use Searchable Names int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; int sum = 0; for (int j = 0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] *realDaysPerIdealDay; int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; }
  • 13. Meaningful Names Use Searchable Names PhoneNumber phoneString; PhoneNumber phone; String NameString; String Name;
  • 14. Meaningful Names Avoid Mental Mapping for (a = 0; a < 10; a++) for (b = 0; b < 10; b++) Class Names Manager, Processor, Data, Info
  • 15. Meaningful Names Avoid Mental Mapping for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) Class Names // Classes and objects should have noun or noun phrase names Customer, WikiPage, Account, AddressParser // a class name should not be a verb
  • 16. Meaningful Names Method Names postPayment, deletePage, save // methods should have verb or verb phrase names // can be prefixed with get , set , is string name = employee.getName(); customer.setName("mike"); if (paycheck.isPosted())...
  • 17. Meaningful Names Don’t be Cute Cuteness in code often appears in the form of colloquialisms or slang. For example, Don’t use the name whack() to mean kill() . Don’t tell little culture dependent jokes like eatMyShorts() to mean abort().
  • 18. Meaningful Names Pick One Word per Concept fetch, retrieve, get // as equivalent methods controller, manager, driver // confusing Don’t Pun // avoid using the same word for two purposes // insert, add
  • 19. Meaningful Names Use Solution Domain Names //AccountVisitor, JobQueue // people who read your code will be programmers //use computer science (CS) terms, algorithm names, pattern names, math terms, and so forth. Add Meaningful Context firstName, lastName, street, city, state, zipcode // a better solution addrFirstName, addrLastName, addrState // a far better solution
  • 20. Meaningful Names Don’t Add Gratuitous Context -> Class Address Address // is a fine name for a class AccountAddress, CustomerAddress // are fine names for instances of the class Address but could be poor names for classes // In an imaginary application called “Gas Station Deluxe,” it is a bad idea to prefix every class with GSD .
  • 21. Functions Rules of Functions // 1. should be small // 2. should be smaller than that // < 150 characters per line // < 20 lines Do One Thing // FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. // THEY SHOULD DO IT ONLY.
  • 22. Functions One Level of Abstraction per Function public void doTheDomesticThings() { takeOutTheTrash(); walkTheDog(); for (Dish dish : dirtyDishStack) { sink.washDish(dish); teaTowel.dryDish(dish); } }
  • 23. Functions One Level of Abstraction per Function public void doTheDomesticThings() { takeOutTheTrash(); walkTheDog(); doTheDishes(); }
  • 24. Functions Single Responsibility Principle In object-oriented programming, the single responsibility principle states that every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Source: WIKI
  • 25. Functions Open / Closed Principle In object-oriented programming, the open/closed principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”. Source : WIKI
  • 26. Functions Use Descriptive Names // isModified or includeSetupAndTeardownPages Function Arguments // the ideal number of arguments for a function is zero
  • 27. Functions Common Monadic Forms // if a function is going to transform its input argument, the transformation should appear as the return value StringBuffer transform(StringBuffer in) // is better than void transform(StringBuffer out)
  • 28. Functions Common Monadic Forms // asking a question about that argument boolean fileExists(“MyFile”) // operating on that argument, transforming and returning it InputStream fileOpen(“MyFile”) // event, use the argument to alter the state of the system void passwordAttemptFailedNtimes(int attempts)
  • 29. Functions Dyadic Functions writeField(name) // is easier to understand than writeField(outputStream, name) // perfectly reasonable Point p = new Point(0,0) // problematic assertEquals(expected, actual)
  • 30. Functions Argument Objects Circle makeCircle(double x, double y, double radius); Circle makeCircle(Point center, double radius); Don’t Repeat Yourself (DRY) // duplication may be the root of all evil in software
  • 31. Functions Structured Programming // Edsger Dijkstra’s rules // one entry // one exit // functions small // occasional multiple return, break, or continue statement
  • 32. Comments Comments Do Not Make Up for Bad Code // don’t comment bad code, rewrite it! Explain Yourself in Code // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) if (employee.isEligibleForFullBenefits())
  • 33. Comments (Good) Legal Comments // Copyright (C) 2011 by Osoco. All rights reserved. Clarification assertTrue(a.compareTo(b) == -1); // a < b assertTrue(b.compareTo(a) == 1); // b > a
  • 34. Comments (Good) Warning of Consequences /SimpleDateFormat is not thread safe, //so we need to create each instance independently. SimpleDateFormat df = new SimpleDateFormat("dd MM yyyy"); TODO Comments
  • 35. Comments (Good) Amplification String listItemContent = match.group(3).trim(); // the trim is real important. It removes the starting // spaces that could cause the item to be recognized // as another list. new ListItemWidget(this, listItemContent, this.level + 1); return buildList(text.substring(match.end()));
  • 36. Comments (Bad) Redundant Comments / Noise Comments /** * The processor delay for this component. */ protected int backgroundProcessorDelay = -1; /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this);
  • 37. Comments (Bad) Journal Comments Changes (from 11-Oct-2001) -------------------------- 11-Oct-2001 : Re-organised the class and moved it to new package com.jrefinery.date (DG); 05-Nov-2001 : Added a getDescription() method, and eliminated NotableDate class (DG);
  • 38. Comments (Bad) - Don’t Use a Comment When You Can Use a Function or a Variable - Commented-Out Code - Attributions and Bylines (added by Sazzad) - HTML Comments
  • 39. Formatting Vertical Distance // variables // should be declared as close to their usage as possible // instance variables // should be declared at the top of the class // dependent functions // if one function calls another, they should be vertically // close, and the caller should be above the called // conceptual affinity // certain bits of code want to be near other bit
  • 40. Formatting Team Rules // every programmer has his own favorite formatting rules // but if he works in a team // then the team rules