SlideShare a Scribd company logo
1 of 26
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

clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summaryJan de Vries
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smellsPaul Nguyen
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean CodeCleanestCode
 
Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)jmiguel rodriguez
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Namenahid035
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
Javascript Clean Code
Javascript Clean CodeJavascript Clean Code
Javascript Clean CodePetra Barus
 
Apresentação Clean Code
Apresentação Clean CodeApresentação Clean Code
Apresentação Clean CodeAndré Leoni
 

What's hot (20)

clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean code
Clean code Clean code
Clean code
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean Code
 
Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Name
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Javascript Clean Code
Javascript Clean CodeJavascript Clean Code
Javascript Clean Code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Apresentação Clean Code
Apresentação Clean CodeApresentação Clean Code
Apresentação Clean Code
 
Clean code
Clean codeClean code
Clean code
 

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 ArchitectsRicardo Wilkins
 
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
 
Hum2310 fa2015 syllabus
Hum2310 fa2015 syllabusHum2310 fa2015 syllabus
Hum2310 fa2015 syllabusProfWillAdams
 
Hum2220 sm2016 syllabus
Hum2220 sm2016 syllabusHum2220 sm2016 syllabus
Hum2220 sm2016 syllabusProfWillAdams
 
Arh2050 sp2016 syllabus
Arh2050 sp2016 syllabusArh2050 sp2016 syllabus
Arh2050 sp2016 syllabusProfWillAdams
 
"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 practicesOpen Education Consortium
 
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 systembetha divya
 
Limited bulgaria presentation
Limited bulgaria presentationLimited bulgaria presentation
Limited bulgaria presentationRealty 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 actUniversity of South Africa (Unisa)
 

Viewers also liked (16)

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
 

Similar to Clean code

Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoringYuriy 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 2019Victor Rentea
 
Sharable of qualities of clean code
Sharable of qualities of clean codeSharable of qualities of clean code
Sharable of qualities of clean codeEman Mohamed
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytechyannick grenzinger
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code cleanBrett Child
 
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 v2Federico Razzoli
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy CodeAndrea Polci
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptxTomas561914
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLIDFoyzul 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 CodeCorrie Bartelheimer
 
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQL
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQLPOUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQL
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQLJacek Gebal
 

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
 
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?
 
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQL
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQLPOUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQL
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQL
 

More from 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 ParsingKnoldus 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 IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus 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.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 

More from Knoldus Inc. (20)

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
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 

Recently uploaded

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

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