SlideShare a Scribd company logo
Clean Code
Pranjut Gogoi
Senior Software Consultant
Knoldus Software LLP
What is clean code ?
Agenda
● Meaningful Names
● Functions
● Comments
● Classes
Meaningful Names
●
Intention Revealing Names
int d; // elapsed time in days
int elapsedTimeInDays;
public List<int[]> getThem() {
– List<int[]> list1 = new ArrayList<int[]>();
– for (int[] x : theList)
– if (x[0] == 4)
– list1.add(x);
– return list1;
– }
Questions
● 1. What kinds of things are in theList ?
● 2. What is the significance of the zeroth
subscript of an item in theList ?
● 3. What is the significance of the value 4 ?
● 4. How would I use the list being returned?
Answers
public List<int[]> getFlaggedCells() {
List<int[]> flaggedCells = new ArrayList<int[]>();
for (int[] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGED)
flaggedCells.add(cell);
return flaggedCells;
}
Avoid Disinformation
XYZControllerForEfficientHandlingOfStrings
XYZControllerForEfficientStorageOfStrings
“Avoid disinformation” = “similar name with
different spelling”
Make Meaningful
Distinctions
● (a1, a2, .. aN)
public static void copyChars(char a1[], char a2[]) {
for (int i = 0; i < a1.length; i++) {
a2[i] = a1[i];
}
}
Use Pronounceable Names
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/** */
};
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;;
private final String recordId = "102";
/* ... */
};
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 j=0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
Avoid Mental Mapping
● Avoid i, j, k
● Be a professional programmer than a smart
programmer
Class names & Method Names
● Class Name should be a Noun
● Method name should be a verb
● Don't be cute with names
Pick One Word per Concept But
don't pun
● For Fetching use only fetch, not retrieve and
get
● Don't pun means don't use add for inserting a
record into the database and adding two
numbers as well.
Domain Names and meaningful
context
● Use domain problem and solution names
● Don't use technical names
● Prefix or suffix for context
Functions
● Small
● Do one thing
● Use Descriptive Names
● Function Arguments
● Have No Side Effects
● Command Query Separation
● Don’t Repeat Yourself
● Structured Programming
Function Arguments
● Niladic is best, Monadic is better, Dyadic is good,
Triad is bad and Polyadic is worst
● Common Monadic Forms : when input gets
changed in the function
● Flag Arguments are ugly.
● Dyadic Functions
● Triad
● Argument Objects
Have No Side Effects
public class UserValidator {
private Cryptographer cryptographer;
public boolean checkPassword(String userName, String password) {
User user = UserGateway.findByName(userName);
if (user != User.NULL) {
String codedPhrase = user.getPhraseEncodedByPassword();
String phrase = cryptographer.decrypt(codedPhrase, password);
if ("Valid Password".equals(phrase)) {
Session.initialize();
return true;
}
}
return false;
}
}
Comments
“Don’t comment bad code—rewrite it.”
Comment practices
● Comments Do Not Make Up for Bad Code
● Explain Yourself in Code
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
Or this?
if (employee.isEligibleForFullBenefits())
● Good Comments
● Bad Comments
Good Comments
● Legal Comments – for copyright and authorship
● Informative Comments
// format matched kk:mm:ss EEE, MMM dd, yyyy
– Pattern timeMatcher = Pattern.compile(
– "d*:d*:d* w*, w* d*, d*");
● Explanation of Intent
● Warning of Consequences
● TODO Comments
● Javadocs in Public APIs
Bad comments
● Mumbling
●
Redundant Comments
●
Misleading Comments
● Mandated Comments
● Journal Comments
●
Noise Comments
●
Position Markers
●
Closing Brace Comments
● Commented-Out Code
●
Too Much Information
Classes
● Variables at the beginning
● Keep class small
● Keep name for determining the responsibility
● Name should be able to described in 25 words.
● Single Responsibility Principle
● Cohesive
● Interfaces and abstract classes
Unit Test
●
1st
law: You may not write production code until
you have written a failing unit test.
●
2nd
law: You may not write more of a unit test than
is sufficient to fail, and not compiling is failing.
●
3rd
law: You may not write more production code
than is sufficient to pass the currently failing test.
● Unit tests are not second class citizen
● Its even more important than the architecture.
What makes a clean test?
● Ans: Three things. Readability, readability, and
readability
● Readibility = clarity, simplicity, density of
expression
● FIRST = Fast Independent Repeatable Self-
Validating Timely
Thank you !!!

More Related Content

What's hot

Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
Visual Engineering
 
Refactoring
RefactoringRefactoring
Refactoring
Tausun Akhtary
 
Clean code
Clean codeClean code
Clean code
Henrique Smoco
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
Ats Uiboupin
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
mh_azad
 
Why you should care about Go (Golang)
Why you should care about Go (Golang)Why you should care about Go (Golang)
Why you should care about Go (Golang)
Aaron Schlesinger
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
Android와 Flutter 앱 개발의 큰 차이점 5가지
Android와 Flutter 앱 개발의 큰 차이점 5가지Android와 Flutter 앱 개발의 큰 차이점 5가지
Android와 Flutter 앱 개발의 큰 차이점 5가지
Bansook Nam
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
Bo-Yi Wu
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
NexThoughts Technologies
 
Clean code
Clean codeClean code
Clean code
Đàm Đàm
 
Clean architecture
Clean architectureClean architecture
Clean architecture
Lieven Doclo
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
CodeOps Technologies LLP
 
Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)
Patricia Aas
 
Clean code: SOLID (iOS)
Clean code: SOLID (iOS)Clean code: SOLID (iOS)
Clean code: SOLID (iOS)
Maksym Husar
 
F# for C# Programmers
F# for C# ProgrammersF# for C# Programmers
F# for C# Programmers
Scott Wlaschin
 
Clean code
Clean code Clean code
Clean code
Achintya Kumar
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
Stephen Colebourne
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
Basil N G
 

What's hot (20)

Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Refactoring
RefactoringRefactoring
Refactoring
 
Clean code
Clean codeClean code
Clean code
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Why you should care about Go (Golang)
Why you should care about Go (Golang)Why you should care about Go (Golang)
Why you should care about Go (Golang)
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Android와 Flutter 앱 개발의 큰 차이점 5가지
Android와 Flutter 앱 개발의 큰 차이점 5가지Android와 Flutter 앱 개발의 큰 차이점 5가지
Android와 Flutter 앱 개발의 큰 차이점 5가지
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
 
Clean code
Clean codeClean code
Clean code
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)
 
Clean code: SOLID (iOS)
Clean code: SOLID (iOS)Clean code: SOLID (iOS)
Clean code: SOLID (iOS)
 
F# for C# Programmers
F# for C# ProgrammersF# for C# Programmers
F# for C# Programmers
 
Clean code
Clean code Clean code
Clean code
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 

Viewers also liked

S.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software ArchitectsS.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software Architects
Ricardo Wilkins
 
PROMPERU - OC Chile 2016
PROMPERU - OC Chile 2016PROMPERU - OC Chile 2016
PROMPERU - OC Chile 2016
agroalimentaria.pe
 
Chateau on the Lake
Chateau on the LakeChateau on the Lake
Chateau on the Lake
Melissa Riley
 
Data protection and privacy framework in the design of learning analytics sys...
Data protection and privacy framework in the design of learning analytics sys...Data protection and privacy framework in the design of learning analytics sys...
Data protection and privacy framework in the design of learning analytics sys...
Tore Hoel
 
Scaling up Open Badges for Open Education
Scaling up Open Badges for Open EducationScaling up Open Badges for Open Education
Scaling up Open Badges for Open Education
Open Education Global (OEGlobal)
 
Hum2310 fa2015 syllabus
Hum2310 fa2015 syllabusHum2310 fa2015 syllabus
Hum2310 fa2015 syllabus
ProfWillAdams
 
Trabajo de power point luis
Trabajo de power point luisTrabajo de power point luis
Trabajo de power point luis
Luis Guillermo Bustamante
 
Hum2220 sm2016 syllabus
Hum2220 sm2016 syllabusHum2220 sm2016 syllabus
Hum2220 sm2016 syllabus
ProfWillAdams
 
Arh2050 sp2016 syllabus
Arh2050 sp2016 syllabusArh2050 sp2016 syllabus
Arh2050 sp2016 syllabus
ProfWillAdams
 
Planificacion familiar
Planificacion familiarPlanificacion familiar
Planificacion familiar
wilmer alberto enriquez sepulveda
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design PrinciplesSerhiy Oplakanets
 
The role of educational developers in supporting open educational practices
The role of educational developers in supporting open educational practicesThe role of educational developers in supporting open educational practices
The role of educational developers in supporting open educational practices
Open Education Global (OEGlobal)
 
review on the performance of grid integrated hybrid system
review on the performance of grid integrated hybrid systemreview on the performance of grid integrated hybrid system
review on the performance of grid integrated hybrid system
betha divya
 
Limited bulgaria presentation
Limited bulgaria presentationLimited bulgaria presentation
Limited bulgaria presentation
Realty Gold World
 
An elephant in the learning analytics room – the obligation to act
An elephant in the learning analytics room –  the obligation to actAn elephant in the learning analytics room –  the obligation to act
An elephant in the learning analytics room – the obligation to act
University of South Africa (Unisa)
 

Viewers also liked (17)

S.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software ArchitectsS.O.L.I.D. Principles for Software Architects
S.O.L.I.D. Principles for Software Architects
 
PROMPERU - OC Chile 2016
PROMPERU - OC Chile 2016PROMPERU - OC Chile 2016
PROMPERU - OC Chile 2016
 
Chateau on the Lake
Chateau on the LakeChateau on the Lake
Chateau on the Lake
 
Data protection and privacy framework in the design of learning analytics sys...
Data protection and privacy framework in the design of learning analytics sys...Data protection and privacy framework in the design of learning analytics sys...
Data protection and privacy framework in the design of learning analytics sys...
 
Scaling up Open Badges for Open Education
Scaling up Open Badges for Open EducationScaling up Open Badges for Open Education
Scaling up Open Badges for Open Education
 
Hum2310 fa2015 syllabus
Hum2310 fa2015 syllabusHum2310 fa2015 syllabus
Hum2310 fa2015 syllabus
 
Trabajo de power point luis
Trabajo de power point luisTrabajo de power point luis
Trabajo de power point luis
 
Hum2220 sm2016 syllabus
Hum2220 sm2016 syllabusHum2220 sm2016 syllabus
Hum2220 sm2016 syllabus
 
Arh2050 sp2016 syllabus
Arh2050 sp2016 syllabusArh2050 sp2016 syllabus
Arh2050 sp2016 syllabus
 
Planificacion familiar
Planificacion familiarPlanificacion familiar
Planificacion familiar
 
Cubism
CubismCubism
Cubism
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles
 
The role of educational developers in supporting open educational practices
The role of educational developers in supporting open educational practicesThe role of educational developers in supporting open educational practices
The role of educational developers in supporting open educational practices
 
review on the performance of grid integrated hybrid system
review on the performance of grid integrated hybrid systemreview on the performance of grid integrated hybrid system
review on the performance of grid integrated hybrid system
 
Limited bulgaria presentation
Limited bulgaria presentationLimited bulgaria presentation
Limited bulgaria presentation
 
An elephant in the learning analytics room – the obligation to act
An elephant in the learning analytics room –  the obligation to actAn elephant in the learning analytics room –  the obligation to act
An elephant in the learning analytics room – the obligation to act
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 

Similar to Clean code

Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoring
Yuriy Gerasimov
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Victor Rentea
 
What's in a name
What's in a nameWhat's in a name
What's in a name
Koby Fruchtnis
 
CLEAN CODE
CLEAN CODECLEAN CODE
CLEAN CODE
Knoldus Inc.
 
Dart workshop
Dart workshopDart workshop
Dart workshop
Vishnu Suresh
 
Software Developer Training
Software Developer TrainingSoftware Developer Training
Software Developer Training
rungwiroon komalittipong
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean code
Eman Mohamed
 
Clean Code
Clean CodeClean Code
Clean Code
Dmytro Turskyi
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
yannick grenzinger
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
Fredrik Wendt
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code clean
Brett Child
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
Sanjeev Kumar Jaiswal
 
How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2
Federico Razzoli
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy Code
Andrea Polci
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
IBM
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptx
Tomas561914
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLID
Foyzul Karim
 
Code Cleanup: A Data Scientist's Guide to Sparkling Code
Code Cleanup: A Data Scientist's Guide to Sparkling CodeCode Cleanup: A Data Scientist's Guide to Sparkling Code
Code Cleanup: A Data Scientist's Guide to Sparkling Code
Corrie Bartelheimer
 
Are You Ready For Clean Code?
Are You Ready For Clean Code?Are You Ready For Clean Code?
Are You Ready For Clean Code?
Whisnu Sucitanuary
 

Similar to Clean code (20)

Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoring
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
What's in a name
What's in a nameWhat's in a name
What's in a name
 
CLEAN CODE
CLEAN CODECLEAN CODE
CLEAN CODE
 
Clean code
Clean codeClean code
Clean code
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
Software Developer Training
Software Developer TrainingSoftware Developer Training
Software Developer Training
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code clean
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2How MySQL can boost (or kill) your application v2
How MySQL can boost (or kill) your application v2
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy Code
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptx
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLID
 
Code Cleanup: A Data Scientist's Guide to Sparkling Code
Code Cleanup: A Data Scientist's Guide to Sparkling CodeCode Cleanup: A Data Scientist's Guide to Sparkling Code
Code Cleanup: A Data Scientist's Guide to Sparkling Code
 
Are You Ready For Clean Code?
Are You Ready For Clean Code?Are You Ready For Clean Code?
Are You Ready For Clean Code?
 

More from Knoldus Inc.

Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
Knoldus Inc.
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
Knoldus Inc.
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
Knoldus Inc.
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
Knoldus Inc.
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
Knoldus Inc.
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
Knoldus Inc.
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
Knoldus Inc.
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
Knoldus Inc.
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
Knoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Knoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
Knoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
Knoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
Knoldus Inc.
 

More from Knoldus Inc. (20)

Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 

Recently uploaded

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
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
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
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
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
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
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
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
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
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
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
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
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
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
 

Recently uploaded (20)

How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
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...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
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
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
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
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
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...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
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 -...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
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
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 

Clean code

  • 1. Clean Code Pranjut Gogoi Senior Software Consultant Knoldus Software LLP
  • 2.
  • 3. What is clean code ?
  • 4. Agenda ● Meaningful Names ● Functions ● Comments ● Classes
  • 5. Meaningful Names ● Intention Revealing Names int d; // elapsed time in days int elapsedTimeInDays; public List<int[]> getThem() { – List<int[]> list1 = new ArrayList<int[]>(); – for (int[] x : theList) – if (x[0] == 4) – list1.add(x); – return list1; – }
  • 6. Questions ● 1. What kinds of things are in theList ? ● 2. What is the significance of the zeroth subscript of an item in theList ? ● 3. What is the significance of the value 4 ? ● 4. How would I use the list being returned?
  • 7. Answers public List<int[]> getFlaggedCells() { List<int[]> flaggedCells = new ArrayList<int[]>(); for (int[] cell : gameBoard) if (cell[STATUS_VALUE] == FLAGGED) flaggedCells.add(cell); return flaggedCells; }
  • 9. Make Meaningful Distinctions ● (a1, a2, .. aN) public static void copyChars(char a1[], char a2[]) { for (int i = 0; i < a1.length; i++) { a2[i] = a1[i]; } }
  • 10. Use Pronounceable Names class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /** */ }; class Customer { private Date generationTimestamp; private Date modificationTimestamp;; private final String recordId = "102"; /* ... */ };
  • 11. 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 j=0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] * realDaysPerIdealDay; int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks;
  • 12. Avoid Mental Mapping ● Avoid i, j, k ● Be a professional programmer than a smart programmer
  • 13. Class names & Method Names ● Class Name should be a Noun ● Method name should be a verb ● Don't be cute with names
  • 14. Pick One Word per Concept But don't pun ● For Fetching use only fetch, not retrieve and get ● Don't pun means don't use add for inserting a record into the database and adding two numbers as well.
  • 15. Domain Names and meaningful context ● Use domain problem and solution names ● Don't use technical names ● Prefix or suffix for context
  • 16. Functions ● Small ● Do one thing ● Use Descriptive Names ● Function Arguments ● Have No Side Effects ● Command Query Separation ● Don’t Repeat Yourself ● Structured Programming
  • 17. Function Arguments ● Niladic is best, Monadic is better, Dyadic is good, Triad is bad and Polyadic is worst ● Common Monadic Forms : when input gets changed in the function ● Flag Arguments are ugly. ● Dyadic Functions ● Triad ● Argument Objects
  • 18. Have No Side Effects public class UserValidator { private Cryptographer cryptographer; public boolean checkPassword(String userName, String password) { User user = UserGateway.findByName(userName); if (user != User.NULL) { String codedPhrase = user.getPhraseEncodedByPassword(); String phrase = cryptographer.decrypt(codedPhrase, password); if ("Valid Password".equals(phrase)) { Session.initialize(); return true; } } return false; } }
  • 19. Comments “Don’t comment bad code—rewrite it.”
  • 20. Comment practices ● Comments Do Not Make Up for Bad Code ● Explain Yourself in Code if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) Or this? if (employee.isEligibleForFullBenefits()) ● Good Comments ● Bad Comments
  • 21. Good Comments ● Legal Comments – for copyright and authorship ● Informative Comments // format matched kk:mm:ss EEE, MMM dd, yyyy – Pattern timeMatcher = Pattern.compile( – "d*:d*:d* w*, w* d*, d*"); ● Explanation of Intent ● Warning of Consequences ● TODO Comments ● Javadocs in Public APIs
  • 22. Bad comments ● Mumbling ● Redundant Comments ● Misleading Comments ● Mandated Comments ● Journal Comments ● Noise Comments ● Position Markers ● Closing Brace Comments ● Commented-Out Code ● Too Much Information
  • 23. Classes ● Variables at the beginning ● Keep class small ● Keep name for determining the responsibility ● Name should be able to described in 25 words. ● Single Responsibility Principle ● Cohesive ● Interfaces and abstract classes
  • 24. Unit Test ● 1st law: You may not write production code until you have written a failing unit test. ● 2nd law: You may not write more of a unit test than is sufficient to fail, and not compiling is failing. ● 3rd law: You may not write more production code than is sufficient to pass the currently failing test. ● Unit tests are not second class citizen ● Its even more important than the architecture.
  • 25. What makes a clean test? ● Ans: Three things. Readability, readability, and readability ● Readibility = clarity, simplicity, density of expression ● FIRST = Fast Independent Repeatable Self- Validating Timely

Editor's Notes

  1. Don&amp;apos;t use a, an, the Zork in a class and thezork in a class
  2. New programmer came and Mohomd bla blac Modi blabla
  3. Class names not Manager, Processor, DATa, Info Yes = Customer, WikiPage, Account Whack() instead of kill() EatMyShorts() instead of abort()
  4. AccountVisitor = in technical it represents the visitor pattern. AddFirstName Context = address
  5. Structure programming = So if you keep your functions small, then the occasional multiple return , break , or continue statement does no harm and can sometimes even be more expressive than the sin-gle-entry, single-exit rule. On the other hand, goto only makes sense in large functions, so it should be avoided. How Do You Write Functions Like This?
  6. Arguments renderForSuite() and renderForSingleTest() . Instead of render(true) Dyadic = assertEquals(expected, actual) Traid = assertEquals(message, expected, actual)
  7. Session.initialize(); creates problem Output Arguments
  8. Legal comments = ide hides it for us Explanation of Intent = for the logic behind something, why we have chosen this logic. Warning of Consequences = we do not need it now, but in older days when junit was not there we should had it.
  9. Mumbling = necessary comments are not sufficient Redundant Comments = head before a function which takes more time to read than the function itself. Mandated Comments = silly to have javadoc for every funciton… it has all function arguments and its description…...we have done that in primoris and its aweful … Journal Comments = journal entry of changes Noise Comments = a comment without any meaning Position Markers = // Actions ///////////////////////// Closing Brace Comments = if{} //if while{} //while
  10. Make it small from the beginning Not like lets make it big first then we will divide it
  11. Duplicate code not expected Meaningful variables FIRST = F - fast I – independent of each other R – repeatable in QA prod, dev S – return boolean T = timely wirte unit test