SlideShare a Scribd company logo
CLEAN CODE
RAJESH KUMAR
1
WHAT IS CLEAN CODE
 I like my code to be elegant and efficient,
 The logic should be straightforward to make it hard for bugs to
hide,
 The dependencies minimal to ease maintenance,
 Error handling is complete,
 Clean code does one thing well.
 Bjarne Stroustrup
2
MEANINGFUL NAMES
 int i;
 What is i?
 int elapsedTime;
 Now we know it is an integer indicating elapsed time.
 But what time? Seconds, years what?
 int elapsedTimeInDays
 Better?
 int elapsedTimeInDaysSinceRestart
3
MEANINGFUL NAMES
 controllerForEfficientHandlingOfStrings
 controllerForEfficientStorageOfStrings
 Frightfully similar
 int a = l;
if ( O == 0 ){
a = O;
}
 Not very clear?
4
MEANINGFUL NAMES
 Names with similar meaning
 accountData vs account
 customerInfo vs customer
 Variable names should be pronounceable
 dtValFmtddmmyy
 dateValueFormattedAsddmmyy
 Use searchable names
 If you have to search a variable named a 
5
NO MAGIC NUMBERS
public List<int[]> getList(List<int[]> inputList) {
List<int[]> tempList = new ArrayList<>();
for (int[] x : inputList)
if (x[0] == 4) tempList.add(x);
return tempList;
}
6
NO MAGIC NUMBERS CONTD
public List<int[]> getFlaggedCells(List<int[]> gameBoard) {
List<int[]> flaggedCells = new ArrayList<>();
for (int[] cell : gameBoard)
if (cell[STATUS_VALUE] == FLAGGED)
flaggedCells.add(cell);
return flaggedCells;
}
7
METHODS
 Method name must be verb
 One name per concept
 Fetch, retrieve, get
 Do not add too much context
 Prefixing everything with application name
 Must always return value
 Should not have side effects
8
METHODS CONTD
 Keep methods small
 Make sure it does one thing
 Niladic, monadic and dyadic
 Triadic is so evil, try enclosing in a class if really required
 So are flag arguments, It means method does more than one thing
9
FUNCTIONS CONTD
 Command query separation
 Method should do something or answer something but not both
 Prefer exceptions to returning error codes
 Violate the command query separation
 The error codes class is dependency magnet
10
WORDS OF WISDOM
 Every function, and every block within a function, should have one
entry and one exit.
 Means that there should only be one return statement in a function,
 no break or continue statements in a loop,
 and never, ever, any goto statements.
 Dijkstra
11
COMMENTS
 What would you prefer?
// Check if employee is eligible for full benefits
if (employee.flag && employee.age > 65)
 Or
if (employee.isEligibleForFullBenefits())
12
COMMENTS
 Do not comment bad code, rewrite it, refactor it
 Kernighan
 If your code can not reveal its intention then the comments shall
neither.
 The comments are seldom maintained
 Comments clutter the code
 TODO comments
13
FORMATTING
 Is as important as the code itself
 Should be standardized for a project
 The old Hollerith limit of 80 is a bit old
14
ABSTRACTION
 Do not blindly create getters and setters
 Understand when to use
 Procedural
 Object oriented
 DTOs do nothing more than to duplicate code
15
ERROR HANDLING
 Use informative error messages
 Do not catch and re-throw
 Use exceptions rather than error codes
 Write try-catch-finally in separate function?
 Checked vs Unchecked exceptions?
 Violates open closed principle
16
TESTS
 F.I.R.S.T. principle
 Tests must be uniquely named
 Given-When-Then
 One assert per test
 Okay to make a function protected to test
 Generally not required if the functions are small
17
CLASSES
 Single Responsibility Principle
 Too many classes
 Look for cohesion
 Dependency Inversion Principle
 Enums vs constants
 Do not inherit constants
18
SYSTEM
 Object creation should be separated from business logic
 Dependency Injection, Factories
 Cross cutting concerns
 Business logic should be separate from framework related code
19
SYSTEM
 Always delete commented code
 And dead code
 Building and deploying a system should be one step
 Should be able to run all tests on local
 Do not override safeties
 Maintain separation between layers
20
QUESTIONS?
21

More Related Content

PPTX
Design Principles
PPTX
Test Driven Development
PPTX
Software Craftsmanship
PPTX
Unit Testing FAQ
PPTX
TDD With Legacy Systems
PPTX
Microservices
PDF
PPTX
Clean code, Feb 2012
Design Principles
Test Driven Development
Software Craftsmanship
Unit Testing FAQ
TDD With Legacy Systems
Microservices
Clean code, Feb 2012

Similar to Clean Code (20)

PPTX
Clean Code - Writing code for human
PDF
Chapter17 of clean code
PPT
Clean code
PPTX
clean code book summary - uncle bob - English version
PDF
Extracts from "Clean Code"
PDF
Extracts from "Clean Code"
PPTX
Clean code
PDF
Extracts from "Clean code"
PPTX
Writing Clean Code (Recommendations by Robert Martin)
PPTX
Clean code
PDF
Clean code and code smells
PDF
Clean Code
PPTX
Coding Checkpoints
PPTX
Clean code slide
PPTX
Clean code - DSC DYPCOE
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
PDF
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
PPTX
R. herves. clean code (theme)2
PPTX
Writing High Quality Code in C#
PPTX
Code reviews
Clean Code - Writing code for human
Chapter17 of clean code
Clean code
clean code book summary - uncle bob - English version
Extracts from "Clean Code"
Extracts from "Clean Code"
Clean code
Extracts from "Clean code"
Writing Clean Code (Recommendations by Robert Martin)
Clean code
Clean code and code smells
Clean Code
Coding Checkpoints
Clean code slide
Clean code - DSC DYPCOE
Clean Code. An Agile Guide to Software Craft Kameron H.
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
R. herves. clean code (theme)2
Writing High Quality Code in C#
Code reviews
Ad

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Cloud computing and distributed systems.
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Network Security Unit 5.pdf for BCA BBA.
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
MYSQL Presentation for SQL database connectivity
Unlocking AI with Model Context Protocol (MCP)
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Machine learning based COVID-19 study performance prediction
Cloud computing and distributed systems.
Review of recent advances in non-invasive hemoglobin estimation
Per capita expenditure prediction using model stacking based on satellite ima...
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Network Security Unit 5.pdf for BCA BBA.
“AI and Expert System Decision Support & Business Intelligence Systems”
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Reach Out and Touch Someone: Haptics and Empathic Computing
The Rise and Fall of 3GPP – Time for a Sabbatical?
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Ad

Clean Code

  • 2. WHAT IS CLEAN CODE  I like my code to be elegant and efficient,  The logic should be straightforward to make it hard for bugs to hide,  The dependencies minimal to ease maintenance,  Error handling is complete,  Clean code does one thing well.  Bjarne Stroustrup 2
  • 3. MEANINGFUL NAMES  int i;  What is i?  int elapsedTime;  Now we know it is an integer indicating elapsed time.  But what time? Seconds, years what?  int elapsedTimeInDays  Better?  int elapsedTimeInDaysSinceRestart 3
  • 4. MEANINGFUL NAMES  controllerForEfficientHandlingOfStrings  controllerForEfficientStorageOfStrings  Frightfully similar  int a = l; if ( O == 0 ){ a = O; }  Not very clear? 4
  • 5. MEANINGFUL NAMES  Names with similar meaning  accountData vs account  customerInfo vs customer  Variable names should be pronounceable  dtValFmtddmmyy  dateValueFormattedAsddmmyy  Use searchable names  If you have to search a variable named a  5
  • 6. NO MAGIC NUMBERS public List<int[]> getList(List<int[]> inputList) { List<int[]> tempList = new ArrayList<>(); for (int[] x : inputList) if (x[0] == 4) tempList.add(x); return tempList; } 6
  • 7. NO MAGIC NUMBERS CONTD public List<int[]> getFlaggedCells(List<int[]> gameBoard) { List<int[]> flaggedCells = new ArrayList<>(); for (int[] cell : gameBoard) if (cell[STATUS_VALUE] == FLAGGED) flaggedCells.add(cell); return flaggedCells; } 7
  • 8. METHODS  Method name must be verb  One name per concept  Fetch, retrieve, get  Do not add too much context  Prefixing everything with application name  Must always return value  Should not have side effects 8
  • 9. METHODS CONTD  Keep methods small  Make sure it does one thing  Niladic, monadic and dyadic  Triadic is so evil, try enclosing in a class if really required  So are flag arguments, It means method does more than one thing 9
  • 10. FUNCTIONS CONTD  Command query separation  Method should do something or answer something but not both  Prefer exceptions to returning error codes  Violate the command query separation  The error codes class is dependency magnet 10
  • 11. WORDS OF WISDOM  Every function, and every block within a function, should have one entry and one exit.  Means that there should only be one return statement in a function,  no break or continue statements in a loop,  and never, ever, any goto statements.  Dijkstra 11
  • 12. COMMENTS  What would you prefer? // Check if employee is eligible for full benefits if (employee.flag && employee.age > 65)  Or if (employee.isEligibleForFullBenefits()) 12
  • 13. COMMENTS  Do not comment bad code, rewrite it, refactor it  Kernighan  If your code can not reveal its intention then the comments shall neither.  The comments are seldom maintained  Comments clutter the code  TODO comments 13
  • 14. FORMATTING  Is as important as the code itself  Should be standardized for a project  The old Hollerith limit of 80 is a bit old 14
  • 15. ABSTRACTION  Do not blindly create getters and setters  Understand when to use  Procedural  Object oriented  DTOs do nothing more than to duplicate code 15
  • 16. ERROR HANDLING  Use informative error messages  Do not catch and re-throw  Use exceptions rather than error codes  Write try-catch-finally in separate function?  Checked vs Unchecked exceptions?  Violates open closed principle 16
  • 17. TESTS  F.I.R.S.T. principle  Tests must be uniquely named  Given-When-Then  One assert per test  Okay to make a function protected to test  Generally not required if the functions are small 17
  • 18. CLASSES  Single Responsibility Principle  Too many classes  Look for cohesion  Dependency Inversion Principle  Enums vs constants  Do not inherit constants 18
  • 19. SYSTEM  Object creation should be separated from business logic  Dependency Injection, Factories  Cross cutting concerns  Business logic should be separate from framework related code 19
  • 20. SYSTEM  Always delete commented code  And dead code  Building and deploying a system should be one step  Should be able to run all tests on local  Do not override safeties  Maintain separation between layers 20