SlideShare a Scribd company logo
Clean Code
// by Ingo Schwarz
What‘s the content?
// try to find a simple definition
What is Clean Code?
// try to convince them, so you don‘t have to force them
Why do I need Clean Code?
// show some simple rules
How to produce Clean Code?
What is Clean Code?
What is Clean Code?
Bjarne Stroustrup
“I like my code to be
elegant and efficient“
“Clean code does
one thing well“
What is Clean Code?
Grady Booch
“Clean code is
Simple and direct“
“Clean code reads like
well-written prose“
What is Clean Code?
Dave Thomas
“Clean code can be read“
“Clean code should
be literate“
What is Clean Code?
Michael Feathers
“Clean Code always looks
like it was written by someone
who cares“
What is Clean Code?
Ward Cunningham
“You know you are working
on clean code, when each routine
you read turns out to be
the pretty much what you
expected“
What is Clean Code?
How to measure good code?
What is Clean Code?
Why do I need Clean Code?
Why do I need Clean Code?
…because you are an author
// YES, YOU ARE!!!
“An author is someone
who practices writing as a profession“
by somebody
Why do I need Clean Code?
…because you don‘t want to be a verb
// NO, YOU DON‘T!!!
“Oh man, this code has been Jimmy’d“
by somebody else
Why do I need Clean Code?
…because you are lazy
// YES, YOU ARE!!!
// so am I
// PROOF: no quotation at this slide
How to produce Clean Code?
How to produce Clean Code?
Robert C. Martin
(aka Uncle Bob)
“The Boy Scout Rule“
How to produce Clean Code?
// General
How to produce Clean Code?
// Naming
“Names are sound and smoke”
Johannes Wolfgang von Goethe – Faust I
How to produce Clean Code?
Take care about names!
// we name everything:
// variables, functions, arguments, classes, packages
// Naming
How to produce Clean Code?
public class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private static final String pszqint = “102“;
}
// Naming
Use Pronounceable Names
How to produce Clean Code?
public class Customer {
private static final String RECORD_ID = “102“;
private Date generationTimestamp;
private Date modificationTimestamp;
}
// Naming
Use Pronounceable Names
How to produce Clean Code?
private String m_dsc;
// Naming
Avoid Encodings (member prefixes)
private PhoneNumber phoneString;
Avoid Encodings (hungarian notation)
How to produce Clean Code?
private String description;
// Naming
Avoid Encodings (member prefixes)
private PhoneNumber phone;
Avoid Encodings (hungarian notation)
How to produce Clean Code?
Add Meaningful Context
fistName, lastName, street, city, state, zipcode
// a better solution
addressFirstName, addressLastName, addressState
// a better solution
Adress myAddress = new Address();
myAddress.getFirstName();
// Naming
How to produce Clean Code?
Small!
Rules of Functions:
1. should be small
2. should be smaller than that
// < 150 characters per line
// < 20 lines
// Functions
How to produce Clean Code?
Do One Thing
Functions should do ONE thing.
They should do it WELL.
They should do it ONLY.
// Functions
How to produce Clean Code?
One Level of Abstraction
// high level of abstraction
getHtml();
// intermediate level of abstraction
String pagePathName = PathParser.getName( pagePath );
// remarkable low level
htmlBuilder.append(“n”);
// Functions
How to produce Clean Code?
Switch Statements
class Employee {
int getSalary() {
switch( getType() ) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new InvalidEmployeeException();
}
}
}
// Functions
How to produce Clean Code?
Switch Statements
interface Employee {
int getSalary();
}
class Salesman implements Employee {
int getSalary() {
return getMonthlySalary() + getCommision();
}
}
class Manager implements Employee {
…
}
// Functions
How to produce Clean Code?
// niladic
getHtml();
// monadic
execute( boolean executionType );
// dyadic
assertEquals(String expected, String actual);
// triadic
drawCircle(double x, double y, double radius);
// Function Arguments
How to produce Clean Code?
Improve Monadic Functions with Flag Argument
// ???
execute( boolean executionType );
// !!!
executeInSuite();
executeStandAlone();
// Function Arguments
How to produce Clean Code?
Improve Dyadic Functions with two similar Argument Types
// ???
assertEquals(String expected, String actual);
assertEquals(String actual, String expected);
// !!!
assertExpectedEqualsActual(expected, actual);
// Function Arguments
How to produce Clean Code?
Improve Triadic Functions with three similar Argument Types
// ???
drawCircle(double x, double y, double radius);
drawCircle(double radius, double x, double y);
// …
// !!!
drawCircle(Point center, double radius);
// Function Arguments
How to produce Clean Code?
Don‘t comment bad code, rewrite it!
// Comments
How to produce Clean Code?
Noise
/** Default Consturctor */
public AnnaulDateRule() { … }
/** The day of the Month. */
private int dayOfMonth();
/** Returns the day of the Month.
@return the day of the Month. */
public int getDayOfMonth() {
return dayOfMonth;
}
// Comments
How to produce Clean Code?
Scary Noise
/** The name. */
private String name;
/** The version. */
private String version;
/** The licenseName. */
private String licenseName;
/** The version. */
private String info;
// Comments
How to produce Clean Code?
Don‘t use comments if you can use a Function/Variable
// does the moduel from the global list <mod> depend on the
// subsystem we are part of?
if(smodule.getDependSubsystems()
.contains(subSysMod.getSubSystem())) { … }
// improved
ArrayList moduleDependencies = module.getDependentSubsystems();
String ourSubsystem = subSystemModule.getSubSystem();
if( moduleDependencies.contains( ourSubsystem ) ) { … }
// Comments
How to produce Clean Code?
The Law of Demeter
// Bad
String outputDir = ctxt.getOptions()
.getScratchDir()
.getAbsolutePath();
// Good
String outputDir = ctxt.getScratchDirPath();
// Data Access
How to produce Clean Code?
Prefer Exceptions to Returning Error Codes
if( deletePage( page ) == E_OK ) {
if( registry.deleteReference(page.name) == E_OK ) {
if( configKeys.deleteKey( page.name.makeKey() ) == E_OK ) {
logger.log(“page deleted”);
} else {
logger.log(“configKey not deleted”);
}
} else {
logger.log(“deleteReference from registry failed”);
}
} else {
logger.log(“delete failed”);
}
// Error Handling
How to produce Clean Code?
Prefer Exceptions to Returning Error Codes
try {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
} catch( Exception e ) {
logger.log(e.getMessage());
}
// Error Handling
How to produce Clean Code?
Extract Try/Catch Blocks
public void delete(Page page) {
try {
deletePageAndAllReferences( page );
} catch ( Exception e ) {
logError( e );
}
}
private void deletePageAndAllReferences(Page page) throws Exception {
deletePage( page );
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
// Error Handling
How to produce Clean Code?
Don‘t return Null
List<Employee> employees = getEmployees();
If( employees != null ) {
for( Employee employee : employees ) {
totalSalary += employee.getSalary();
}
}
// Error Handling
How to produce Clean Code?
Don‘t return Null
List<Employee> employees = getEmployees(); 
for( Employee employee : employees ) {
totalSalary += employee.getSalary();
}
// Error Handling
How to produce Clean Code?
Small!
Rules of Classes:
1. should be small
2. should be smaller than that
// Single Responsibility Principle (SRP)
// a class should have one, and only one, readon to change
// Classes
How to produce Clean Code?
// More Information
Have a look at:
Clean Code
Clean Code
Ad

More Related Content

What's hot (20)

Clean Code
Clean CodeClean Code
Clean Code
swaraj Patil
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
Angel Garcia Olloqui
 
Clean code
Clean codeClean code
Clean code
Mahmoud Zizo
 
Clean code
Clean codeClean code
Clean code
Duc Nguyen Quang
 
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
saber tabatabaee
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
YeurDreamin'
 
Clean code
Clean code Clean code
Clean code
Achintya Kumar
 
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
Geshan Manandhar
 
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#
Asim Rais Siddiqui
 
Clean Code
Clean CodeClean Code
Clean Code
Dmytro Turskyi
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
Clean code
Clean codeClean code
Clean code
Khou Suylong
 
Clean Code
Clean CodeClean Code
Clean Code
Victor Rentea
 
Coding standards and guidelines
Coding standards and guidelinesCoding standards and guidelines
Coding standards and guidelines
brijraj_singh
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
Victor Rentea
 
Java interface
Java interfaceJava interface
Java interface
Md. Tanvir Hossain
 
Clean code coding like a professional
Clean code   coding like a professionalClean code   coding like a professional
Clean code coding like a professional
Nhật Nguyễn Khắc
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
 

Similar to Clean Code (20)

F# as our day job by 2016
F# as our day job by 2016F# as our day job by 2016
F# as our day job by 2016
Tomas Jansson
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
Bob Paulin
 
Agileee Developers Toolkit In The Agile World
Agileee Developers Toolkit In The Agile WorldAgileee Developers Toolkit In The Agile World
Agileee Developers Toolkit In The Agile World
Agileee
 
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
Dror Helper
 
Pyramid of-developer-skills
Pyramid of-developer-skillsPyramid of-developer-skills
Pyramid of-developer-skills
Alexandru Bolboaca
 
JVM Performance Magic Tricks
JVM Performance Magic TricksJVM Performance Magic Tricks
JVM Performance Magic Tricks
Takipi
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
Gianluca Padovani
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
Ortus Solutions, Corp
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLEAN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
Gavin Pickin
 
resolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bddresolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bdd
Rodrigo Urubatan
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
David Gómez García
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
🏁 Pierre-Henry Soria 💡
 
Improving MariaDB Server Code Health
Improving MariaDB Server Code HealthImproving MariaDB Server Code Health
Improving MariaDB Server Code Health
Vicentiu Ciorbaru
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
Fredrik Wendt
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at Jet
C4Media
 
Art of unit testing: how to do it right
Art of unit testing: how to do it rightArt of unit testing: how to do it right
Art of unit testing: how to do it right
Dmytro Patserkovskyi
 
Rubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDDRubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDD
Rodrigo Urubatan
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
aeden_brines
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
Trivuz ত্রিভুজ
 
F# as our day job by 2016
F# as our day job by 2016F# as our day job by 2016
F# as our day job by 2016
Tomas Jansson
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
Bob Paulin
 
Agileee Developers Toolkit In The Agile World
Agileee Developers Toolkit In The Agile WorldAgileee Developers Toolkit In The Agile World
Agileee Developers Toolkit In The Agile World
Agileee
 
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
Dror Helper
 
JVM Performance Magic Tricks
JVM Performance Magic TricksJVM Performance Magic Tricks
JVM Performance Magic Tricks
Takipi
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017
Ortus Solutions, Corp
 
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLEAN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
Gavin Pickin
 
resolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bddresolvendo problemas de comunicação em equipes distribuídas com bdd
resolvendo problemas de comunicação em equipes distribuídas com bdd
Rodrigo Urubatan
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
Improving MariaDB Server Code Health
Improving MariaDB Server Code HealthImproving MariaDB Server Code Health
Improving MariaDB Server Code Health
Vicentiu Ciorbaru
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at Jet
C4Media
 
Art of unit testing: how to do it right
Art of unit testing: how to do it rightArt of unit testing: how to do it right
Art of unit testing: how to do it right
Dmytro Patserkovskyi
 
Rubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDDRubyconf2016 - Solving communication problems in distributed teams with BDD
Rubyconf2016 - Solving communication problems in distributed teams with BDD
Rodrigo Urubatan
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
aeden_brines
 
Ad

Recently uploaded (20)

LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Ad

Clean Code

  • 2. What‘s the content? // try to find a simple definition What is Clean Code? // try to convince them, so you don‘t have to force them Why do I need Clean Code? // show some simple rules How to produce Clean Code?
  • 4. What is Clean Code? Bjarne Stroustrup “I like my code to be elegant and efficient“ “Clean code does one thing well“
  • 5. What is Clean Code? Grady Booch “Clean code is Simple and direct“ “Clean code reads like well-written prose“
  • 6. What is Clean Code? Dave Thomas “Clean code can be read“ “Clean code should be literate“
  • 7. What is Clean Code? Michael Feathers “Clean Code always looks like it was written by someone who cares“
  • 8. What is Clean Code? Ward Cunningham “You know you are working on clean code, when each routine you read turns out to be the pretty much what you expected“
  • 9. What is Clean Code? How to measure good code?
  • 12. Why do I need Clean Code? …because you are an author // YES, YOU ARE!!! “An author is someone who practices writing as a profession“ by somebody
  • 13. Why do I need Clean Code? …because you don‘t want to be a verb // NO, YOU DON‘T!!! “Oh man, this code has been Jimmy’d“ by somebody else
  • 14. Why do I need Clean Code? …because you are lazy // YES, YOU ARE!!! // so am I // PROOF: no quotation at this slide
  • 15. How to produce Clean Code?
  • 16. How to produce Clean Code?
  • 17. Robert C. Martin (aka Uncle Bob) “The Boy Scout Rule“ How to produce Clean Code? // General
  • 18. How to produce Clean Code? // Naming “Names are sound and smoke” Johannes Wolfgang von Goethe – Faust I
  • 19. How to produce Clean Code? Take care about names! // we name everything: // variables, functions, arguments, classes, packages // Naming
  • 20. How to produce Clean Code? public class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private static final String pszqint = “102“; } // Naming Use Pronounceable Names
  • 21. How to produce Clean Code? public class Customer { private static final String RECORD_ID = “102“; private Date generationTimestamp; private Date modificationTimestamp; } // Naming Use Pronounceable Names
  • 22. How to produce Clean Code? private String m_dsc; // Naming Avoid Encodings (member prefixes) private PhoneNumber phoneString; Avoid Encodings (hungarian notation)
  • 23. How to produce Clean Code? private String description; // Naming Avoid Encodings (member prefixes) private PhoneNumber phone; Avoid Encodings (hungarian notation)
  • 24. How to produce Clean Code? Add Meaningful Context fistName, lastName, street, city, state, zipcode // a better solution addressFirstName, addressLastName, addressState // a better solution Adress myAddress = new Address(); myAddress.getFirstName(); // Naming
  • 25. How to produce Clean Code? Small! Rules of Functions: 1. should be small 2. should be smaller than that // < 150 characters per line // < 20 lines // Functions
  • 26. How to produce Clean Code? Do One Thing Functions should do ONE thing. They should do it WELL. They should do it ONLY. // Functions
  • 27. How to produce Clean Code? One Level of Abstraction // high level of abstraction getHtml(); // intermediate level of abstraction String pagePathName = PathParser.getName( pagePath ); // remarkable low level htmlBuilder.append(“n”); // Functions
  • 28. How to produce Clean Code? Switch Statements class Employee { int getSalary() { switch( getType() ) { case EmployeeType.ENGINEER: return _monthlySalary; case EmployeeType.SALESMAN: return _monthlySalary + _commission; case EmployeeType.MANAGER: return _monthlySalary + _bonus; default: throw new InvalidEmployeeException(); } } } // Functions
  • 29. How to produce Clean Code? Switch Statements interface Employee { int getSalary(); } class Salesman implements Employee { int getSalary() { return getMonthlySalary() + getCommision(); } } class Manager implements Employee { … } // Functions
  • 30. How to produce Clean Code? // niladic getHtml(); // monadic execute( boolean executionType ); // dyadic assertEquals(String expected, String actual); // triadic drawCircle(double x, double y, double radius); // Function Arguments
  • 31. How to produce Clean Code? Improve Monadic Functions with Flag Argument // ??? execute( boolean executionType ); // !!! executeInSuite(); executeStandAlone(); // Function Arguments
  • 32. How to produce Clean Code? Improve Dyadic Functions with two similar Argument Types // ??? assertEquals(String expected, String actual); assertEquals(String actual, String expected); // !!! assertExpectedEqualsActual(expected, actual); // Function Arguments
  • 33. How to produce Clean Code? Improve Triadic Functions with three similar Argument Types // ??? drawCircle(double x, double y, double radius); drawCircle(double radius, double x, double y); // … // !!! drawCircle(Point center, double radius); // Function Arguments
  • 34. How to produce Clean Code? Don‘t comment bad code, rewrite it! // Comments
  • 35. How to produce Clean Code? Noise /** Default Consturctor */ public AnnaulDateRule() { … } /** The day of the Month. */ private int dayOfMonth(); /** Returns the day of the Month. @return the day of the Month. */ public int getDayOfMonth() { return dayOfMonth; } // Comments
  • 36. How to produce Clean Code? Scary Noise /** The name. */ private String name; /** The version. */ private String version; /** The licenseName. */ private String licenseName; /** The version. */ private String info; // Comments
  • 37. How to produce Clean Code? Don‘t use comments if you can use a Function/Variable // does the moduel from the global list <mod> depend on the // subsystem we are part of? if(smodule.getDependSubsystems() .contains(subSysMod.getSubSystem())) { … } // improved ArrayList moduleDependencies = module.getDependentSubsystems(); String ourSubsystem = subSystemModule.getSubSystem(); if( moduleDependencies.contains( ourSubsystem ) ) { … } // Comments
  • 38. How to produce Clean Code? The Law of Demeter // Bad String outputDir = ctxt.getOptions() .getScratchDir() .getAbsolutePath(); // Good String outputDir = ctxt.getScratchDirPath(); // Data Access
  • 39. How to produce Clean Code? Prefer Exceptions to Returning Error Codes if( deletePage( page ) == E_OK ) { if( registry.deleteReference(page.name) == E_OK ) { if( configKeys.deleteKey( page.name.makeKey() ) == E_OK ) { logger.log(“page deleted”); } else { logger.log(“configKey not deleted”); } } else { logger.log(“deleteReference from registry failed”); } } else { logger.log(“delete failed”); } // Error Handling
  • 40. How to produce Clean Code? Prefer Exceptions to Returning Error Codes try { deletePage(page); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); } catch( Exception e ) { logger.log(e.getMessage()); } // Error Handling
  • 41. How to produce Clean Code? Extract Try/Catch Blocks public void delete(Page page) { try { deletePageAndAllReferences( page ); } catch ( Exception e ) { logError( e ); } } private void deletePageAndAllReferences(Page page) throws Exception { deletePage( page ); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); } // Error Handling
  • 42. How to produce Clean Code? Don‘t return Null List<Employee> employees = getEmployees(); If( employees != null ) { for( Employee employee : employees ) { totalSalary += employee.getSalary(); } } // Error Handling
  • 43. How to produce Clean Code? Don‘t return Null List<Employee> employees = getEmployees();  for( Employee employee : employees ) { totalSalary += employee.getSalary(); } // Error Handling
  • 44. How to produce Clean Code? Small! Rules of Classes: 1. should be small 2. should be smaller than that // Single Responsibility Principle (SRP) // a class should have one, and only one, readon to change // Classes
  • 45. How to produce Clean Code? // More Information Have a look at:

Editor's Notes

  • #5: Inventor of C++
  • #6: Author of „Object Oriented Analysis and Design with Applications“ -> fundamentals of UML
  • #7: Author of „The Programmatic Programmer“ and created the phrases ‚Code Kata‘ and ‚DRY‘
  • #8: Author of „Working Effectively woth legacy Code“
  • #9: Inventor of Wiki coinventor of eXtreme Programming Motive force behinde Design Patterns
  • #13: Want to impress your mom? Tell her you’re an author! An author is someone who practices writing as a profession. Developers write all day. It’s easy to forget that each line of code we write is likely to be read 10 or more times by humans during its lifetime. These humans are our fellow co-workers. (fixing bugs and adding features) Great authors are known for writing books that tell a clear, compelling story. They use tools like chapters, headings, and paragraphs to clearly organize their thoughts and painlessly guide their reader. Developers work in a very similar system, but simply use different jargon of namespaces, classes, and methods.
  • #14: Everyone knows the previous co-worker whose name became a verb to describe dirty code.
  • #15: laziness can be a positive attribute in the right context. As I stumbled through writing code in my early years, I learned the hard way that writing clean code really pays off. Professional developers strive to be the good kind of lazy. This laziness is based on putting extra care into the code so that it’s not so hard to write up front, and it’s easier to work with later. Code read to write ratio is 10:1 -> like Database -> brain sucks as cache
  • #39: Shy Code
  • #42: Error handling is ONE THING