SlideShare a Scribd company logo
1 of 35
Clean Code
HENRIQUE SMOCO
Software Develop
Software Maintenance
 % of time spent reading code vs writing it
 Intellectually Complex
 Documentation?
 If it’s not broken, don’t fix it
 More difficult at each iteration
Clean Code Definition
 Works
 Easy to read
 Easy to understand
 Easy to extend
 Efficient (straight to the point)
 Clean (someone cared)
Clean Code Metrics
“Any fool can write code that a
computer can understand. Good
programmers write code that
humans can understand.”
MARTIN FOWLER, 2008
How to write better?
Write for others
 Always code as if the guy who ends up maintaining
your code will be a violent psychopath who knows
where you live!
Boy Scout Rule
 Always leave the campground cleaner than you found
it.
Care about
 Even if it’s only to correct formatting
 Avoid the “Broken Window Theory”
Broken Window Theory: https://blog.codinghorror.com/the-broken-window-theory
Don’t Reinvent the Whell
 Before writing, ask if someone already did or if there is
any lib that do what is needed
 Less is more!
Study, ask, share
Dirty Code
CODE SMELLS
Detecting Bad Code
 Not used code
 Duplicated code
 Methods with lots of parameters
 Long methods (20 lines or more)
 Conditional Complexity
 Speculative Generality
 Comments (what instead of why)
For a thorough list, access: http://www.codinghorror.com/blog/2006/05/code-smells.html
Clean Code
General Concepts
 Help the next one, because the next one can be you
 Don’t create abstractions thinking about the future
 Don't be afraid of changing things, in the worst case it was
already broken
 Don't optimize prematurely
 Prefer composition over inheritance
 Avoid static methods/singletons
 Delete code is more fun than create it
Use Meaningful Names
 Use names that reveal intent
 Give preference to client language
(Ubiquitous Language)
 Don’t economize chars
 Don’t be funny
 Avoid prefixes (strMyVariable)
 If it's not clear, rename it
 Don't use characteristics of the variable
 Date yyyyMMdd = ...
 Color blue = Color.RED; //BAD CODE
Use Meaningful Names
public List<Cell> getCells() {
List<Cell> lst = new ArrayList<Cell>();
for (Cell c : data)
if (c.getStatus() == 4)
lst.add(c);
return lst;
}
Use Meaningful Names
public List<Cell> getMarkedCells() {
List<Cell> markedCells = new ArrayList<>();
for (Cell cell : gameBoard)
if (cell.isMarked()) {
markedCells.add(cell);
}
return markedCells;
}
Clean Methods
 Should be small
 Really, small than that
 Should do only one thing (SRP)
 Better if organized top to bottom
 Avoid global variables, use parameters
 Doesn’t has side effects
 One input, one output
 Doesn’t has duplicated code (DRY)
 Lots of parameters? Change for a class
Clean Methods
public void printUserName(int userCode) {
Usuario user = getUser (userCode);
if (exists(user)) {
printOnConsole(user.getName());
}
}
private User getUser(int userCode) {
return dao.getUser(userCode);
}
private boolean exists(User user) {
return user != null;
}
private void printOnConsole(String message) {
system.out.println(message);
}
Clean Methods
public void printUserName(int userCode) {
Usuario user = getUser (userCode);
if (exists(user)) {
printOnConsole(user.getName());
}
}
private User getUser(int userCode) {
return dao.getUser(userCode);
}
private boolean exists(User user) {
return user != null;
}
private void printOnConsole(String message) {
system.out.println(message);
}
Clean Methods
public void printUserName(int userCode) {
Usuario user = getUser (userCode);
if (exists(user)) {
printOnConsole(user.getName());
}
}
private User getUser(int userCode) {
return dao.getUser(userCode);
}
private boolean exists(User user) {
return user != null;
}
private void printOnConsole(String message) {
system.out.println(message);
}
Clean Methods
public void printUserName(int userCode) {
Usuario user = getUser (userCode);
if (exists(user)) {
printOnConsole(user.getName());
}
}
private User getUser(int userCode) {
return dao.getUser(userCode);
}
private boolean exists(User user) {
return user != null;
}
private void printOnConsole(String message) {
system.out.println(message);
}
Clean Comments
 Explain why, not what
 Avoid redundancy
//Get a list of users
List users = getUsers();
//Get the users again so we can check what changed
List users = getUsers();
Clean Comments
 If you need comments, probably you should create a
method instead
List clientIds = ...
//Get clientes from database
for (Client cli : clientIds) {
...
}
List clientIds = ...
getClientsFromDatabase(clientIds);
Clean Comments
// Verify if employee has all benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
if (employee.hasAllBenefits())
Clean Comments
while ((line = in.readLine()) != null) {
...
} //end while
// InputStream results = formatter.getResultStream();
// Reader reader = new StreamReader(results);
//TODO Validate received code
Clean Formatting
 The goal isto make communication better
 Follow the formatting pattern of the team/project
 Declare variables as close as possible where they are
used
 Always use curly braces
if (loggedIn) {
loginsCount++;
}
Clean Formatting
 Use vertical grouping to separate code
List clients = ...
premiumClients = selectPremiumClients(clients);
saveFlagBillSent(premiumClients);
saveProcessLog(premiumClients, successMsg);
sendBillTo(premiumClients);
sendEmailBillAvailable(premiumClients);
Clean Exception Handling
 You can log the exception or throw it, never both
 Use log4j (or others), System.out is bad
 Give preference to RuntimeException
Clean Exception Handling
public void delete(Page page) {
try {
deletePageAndAllReferences(page);
} catch (Exception e) {
logger.log(e.getMessage());
}
}
private void deletePageAndAllReferences(Page page) throws
Exception {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
Clean Exception Handling
 Whenever possible, DON’T return null
List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}
}
public List<Employee> getEmployees() {
if( .. there are no employees .. ) {
return Collections.emptyList();
}
}
Clean Tests
 Give the tests the same love as production code
 Give preference to unit tests
 Assert one concept per test
 Assert one concept per test (important)
 Always run all (unit) tests
 Don’t use test class constructor, use @Before and
@BeforeClass
 Avoid manual setup/verifications
 The simpler the better
Clean Code
IT’S UP TO YOU TOO!
Clean code

More Related Content

What's hot

What's hot (20)

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
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Clean code
Clean code Clean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean code
Clean codeClean code
Clean code
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
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
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
Clean Code
Clean CodeClean Code
Clean Code
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Coding standards
Coding standardsCoding standards
Coding standards
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Name
 

Viewers also liked

生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)
生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)
生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)Takumi Ohno
 
Observe some unemployed people and note down thier daily routine
Observe some unemployed people and note down thier daily routineObserve some unemployed people and note down thier daily routine
Observe some unemployed people and note down thier daily routineGufran Shaikh
 
Hiatal hernias
Hiatal herniasHiatal hernias
Hiatal herniasLeor Arbel
 
Presentación1 de Semiotica de la Arquitectura
Presentación1 de Semiotica de la ArquitecturaPresentación1 de Semiotica de la Arquitectura
Presentación1 de Semiotica de la ArquitecturaPedrov Hernandez
 
Presentacion dioscar ley de victima
Presentacion dioscar ley de victimaPresentacion dioscar ley de victima
Presentacion dioscar ley de victimadioscar ramones
 
3Com 6000M-RCTL
3Com 6000M-RCTL3Com 6000M-RCTL
3Com 6000M-RCTLsavomir
 
C- Programs - Harsh
C- Programs - HarshC- Programs - Harsh
C- Programs - HarshHarsh Sharma
 
Brief historyofwhiskey[3]
Brief historyofwhiskey[3]Brief historyofwhiskey[3]
Brief historyofwhiskey[3]murman4fun
 
Iwein fuld-elegant-code-google-queries
Iwein fuld-elegant-code-google-queriesIwein fuld-elegant-code-google-queries
Iwein fuld-elegant-code-google-queriesIwein Fuld
 
Prepare your air conditioner for summer
Prepare your air conditioner for summerPrepare your air conditioner for summer
Prepare your air conditioner for summerWhitney Bennett
 
Multistory building windows cleaning process
Multistory building windows cleaning processMultistory building windows cleaning process
Multistory building windows cleaning processARS Ltd
 
Clean code and the clean coders
Clean code and the clean codersClean code and the clean coders
Clean code and the clean codersluisartola
 
Air Conditioning System
Air Conditioning SystemAir Conditioning System
Air Conditioning SystemSumit Ranjan
 

Viewers also liked (17)

生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)
生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)
生き残る文房具業界〜なぜデジタルの時代に、アナログの文房具は生き残っているのか〜(2014年)
 
Observe some unemployed people and note down thier daily routine
Observe some unemployed people and note down thier daily routineObserve some unemployed people and note down thier daily routine
Observe some unemployed people and note down thier daily routine
 
Costs of production
Costs of productionCosts of production
Costs of production
 
Hiatal hernias
Hiatal herniasHiatal hernias
Hiatal hernias
 
Presentación1 de Semiotica de la Arquitectura
Presentación1 de Semiotica de la ArquitecturaPresentación1 de Semiotica de la Arquitectura
Presentación1 de Semiotica de la Arquitectura
 
PLANES DEL MINEDU PARA 2017
PLANES DEL MINEDU PARA 2017PLANES DEL MINEDU PARA 2017
PLANES DEL MINEDU PARA 2017
 
Presentacion dioscar ley de victima
Presentacion dioscar ley de victimaPresentacion dioscar ley de victima
Presentacion dioscar ley de victima
 
3Com 6000M-RCTL
3Com 6000M-RCTL3Com 6000M-RCTL
3Com 6000M-RCTL
 
C- Programs - Harsh
C- Programs - HarshC- Programs - Harsh
C- Programs - Harsh
 
Videojuego
VideojuegoVideojuego
Videojuego
 
Evaluación de desempeño directivo UGEL Y DRE
Evaluación de desempeño directivo UGEL Y DREEvaluación de desempeño directivo UGEL Y DRE
Evaluación de desempeño directivo UGEL Y DRE
 
Brief historyofwhiskey[3]
Brief historyofwhiskey[3]Brief historyofwhiskey[3]
Brief historyofwhiskey[3]
 
Iwein fuld-elegant-code-google-queries
Iwein fuld-elegant-code-google-queriesIwein fuld-elegant-code-google-queries
Iwein fuld-elegant-code-google-queries
 
Prepare your air conditioner for summer
Prepare your air conditioner for summerPrepare your air conditioner for summer
Prepare your air conditioner for summer
 
Multistory building windows cleaning process
Multistory building windows cleaning processMultistory building windows cleaning process
Multistory building windows cleaning process
 
Clean code and the clean coders
Clean code and the clean codersClean code and the clean coders
Clean code and the clean coders
 
Air Conditioning System
Air Conditioning SystemAir Conditioning System
Air Conditioning System
 

Similar to Clean code

C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and ToolsBob Paulin
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeBen Marks
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patternsPascal Larocque
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldDavid McCarter
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean CodeCleanestCode
 

Similar to Clean code (20)

Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Code Metrics
Code MetricsCode Metrics
Code Metrics
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
Refactoring
RefactoringRefactoring
Refactoring
 
Code review
Code reviewCode review
Code review
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
 
Coding standard
Coding standardCoding standard
Coding standard
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento Code
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean Code
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Recently uploaded (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Clean code

  • 2. Software Develop Software Maintenance  % of time spent reading code vs writing it  Intellectually Complex  Documentation?  If it’s not broken, don’t fix it  More difficult at each iteration
  • 3. Clean Code Definition  Works  Easy to read  Easy to understand  Easy to extend  Efficient (straight to the point)  Clean (someone cared)
  • 5. “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” MARTIN FOWLER, 2008
  • 6. How to write better?
  • 7. Write for others  Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live!
  • 8. Boy Scout Rule  Always leave the campground cleaner than you found it.
  • 9. Care about  Even if it’s only to correct formatting  Avoid the “Broken Window Theory” Broken Window Theory: https://blog.codinghorror.com/the-broken-window-theory
  • 10. Don’t Reinvent the Whell  Before writing, ask if someone already did or if there is any lib that do what is needed  Less is more!
  • 13. Detecting Bad Code  Not used code  Duplicated code  Methods with lots of parameters  Long methods (20 lines or more)  Conditional Complexity  Speculative Generality  Comments (what instead of why) For a thorough list, access: http://www.codinghorror.com/blog/2006/05/code-smells.html
  • 15. General Concepts  Help the next one, because the next one can be you  Don’t create abstractions thinking about the future  Don't be afraid of changing things, in the worst case it was already broken  Don't optimize prematurely  Prefer composition over inheritance  Avoid static methods/singletons  Delete code is more fun than create it
  • 16. Use Meaningful Names  Use names that reveal intent  Give preference to client language (Ubiquitous Language)  Don’t economize chars  Don’t be funny  Avoid prefixes (strMyVariable)  If it's not clear, rename it  Don't use characteristics of the variable  Date yyyyMMdd = ...  Color blue = Color.RED; //BAD CODE
  • 17. Use Meaningful Names public List<Cell> getCells() { List<Cell> lst = new ArrayList<Cell>(); for (Cell c : data) if (c.getStatus() == 4) lst.add(c); return lst; }
  • 18. Use Meaningful Names public List<Cell> getMarkedCells() { List<Cell> markedCells = new ArrayList<>(); for (Cell cell : gameBoard) if (cell.isMarked()) { markedCells.add(cell); } return markedCells; }
  • 19. Clean Methods  Should be small  Really, small than that  Should do only one thing (SRP)  Better if organized top to bottom  Avoid global variables, use parameters  Doesn’t has side effects  One input, one output  Doesn’t has duplicated code (DRY)  Lots of parameters? Change for a class
  • 20. Clean Methods public void printUserName(int userCode) { Usuario user = getUser (userCode); if (exists(user)) { printOnConsole(user.getName()); } } private User getUser(int userCode) { return dao.getUser(userCode); } private boolean exists(User user) { return user != null; } private void printOnConsole(String message) { system.out.println(message); }
  • 21. Clean Methods public void printUserName(int userCode) { Usuario user = getUser (userCode); if (exists(user)) { printOnConsole(user.getName()); } } private User getUser(int userCode) { return dao.getUser(userCode); } private boolean exists(User user) { return user != null; } private void printOnConsole(String message) { system.out.println(message); }
  • 22. Clean Methods public void printUserName(int userCode) { Usuario user = getUser (userCode); if (exists(user)) { printOnConsole(user.getName()); } } private User getUser(int userCode) { return dao.getUser(userCode); } private boolean exists(User user) { return user != null; } private void printOnConsole(String message) { system.out.println(message); }
  • 23. Clean Methods public void printUserName(int userCode) { Usuario user = getUser (userCode); if (exists(user)) { printOnConsole(user.getName()); } } private User getUser(int userCode) { return dao.getUser(userCode); } private boolean exists(User user) { return user != null; } private void printOnConsole(String message) { system.out.println(message); }
  • 24. Clean Comments  Explain why, not what  Avoid redundancy //Get a list of users List users = getUsers(); //Get the users again so we can check what changed List users = getUsers();
  • 25. Clean Comments  If you need comments, probably you should create a method instead List clientIds = ... //Get clientes from database for (Client cli : clientIds) { ... } List clientIds = ... getClientsFromDatabase(clientIds);
  • 26. Clean Comments // Verify if employee has all benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) if (employee.hasAllBenefits())
  • 27. Clean Comments while ((line = in.readLine()) != null) { ... } //end while // InputStream results = formatter.getResultStream(); // Reader reader = new StreamReader(results); //TODO Validate received code
  • 28. Clean Formatting  The goal isto make communication better  Follow the formatting pattern of the team/project  Declare variables as close as possible where they are used  Always use curly braces if (loggedIn) { loginsCount++; }
  • 29. Clean Formatting  Use vertical grouping to separate code List clients = ... premiumClients = selectPremiumClients(clients); saveFlagBillSent(premiumClients); saveProcessLog(premiumClients, successMsg); sendBillTo(premiumClients); sendEmailBillAvailable(premiumClients);
  • 30. Clean Exception Handling  You can log the exception or throw it, never both  Use log4j (or others), System.out is bad  Give preference to RuntimeException
  • 31. Clean Exception Handling public void delete(Page page) { try { deletePageAndAllReferences(page); } catch (Exception e) { logger.log(e.getMessage()); } } private void deletePageAndAllReferences(Page page) throws Exception { deletePage(page); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); }
  • 32. Clean Exception Handling  Whenever possible, DON’T return null List<Employee> employees = getEmployees(); for(Employee e : employees) { totalPay += e.getPay(); } } public List<Employee> getEmployees() { if( .. there are no employees .. ) { return Collections.emptyList(); } }
  • 33. Clean Tests  Give the tests the same love as production code  Give preference to unit tests  Assert one concept per test  Assert one concept per test (important)  Always run all (unit) tests  Don’t use test class constructor, use @Before and @BeforeClass  Avoid manual setup/verifications  The simpler the better
  • 34. Clean Code IT’S UP TO YOU TOO!