SlideShare ist ein Scribd-Unternehmen logo
1 von 47
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

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
 
Clean code
Clean codeClean code
Clean code
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
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: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit TestsClean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit Tests
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean code Clean code
Clean code
 
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 and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
C functions
C functionsC functions
C functions
 

Ähnlich wie Clean Code

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 2016Tomas Jansson
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and ToolsBob 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 WorldAgileee
 
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 .NETDror Helper
 
JVM Performance Magic Tricks
JVM Performance Magic TricksJVM Performance Magic Tricks
JVM Performance Magic TricksTakipi
 
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 MAINTAINABLEGavin Pickin
 
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() 2017Ortus Solutions, Corp
 
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 bddRodrigo 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 HealthVicentiu Ciorbaru
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at JetC4Media
 
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 rightDmytro 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 BDDRodrigo Urubatan
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)aeden_brines
 

Ähnlich wie 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
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
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
 
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
 
Pyramid of-developer-skills
Pyramid of-developer-skillsPyramid of-developer-skills
Pyramid of-developer-skills
 
JVM Performance Magic Tricks
JVM Performance Magic TricksJVM Performance Magic Tricks
JVM Performance Magic Tricks
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
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
 
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
 
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
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
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...
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
 
Improving MariaDB Server Code Health
Improving MariaDB Server Code HealthImproving MariaDB Server Code Health
Improving MariaDB Server Code Health
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at Jet
 
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
 
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
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 

Kürzlich hochgeladen

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
+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
 
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
 
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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 

Kürzlich hochgeladen (20)

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
+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...
 
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...
 
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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
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 🔝✔️✔️
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 

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:

Hinweis der Redaktion

  1. Inventor of C++
  2. Author of „Object Oriented Analysis and Design with Applications“ -> fundamentals of UML
  3. Author of „The Programmatic Programmer“ and created the phrases ‚Code Kata‘ and ‚DRY‘
  4. Author of „Working Effectively woth legacy Code“
  5. Inventor of Wiki coinventor of eXtreme Programming Motive force behinde Design Patterns
  6. 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.
  7. Everyone knows the previous co-worker whose name became a verb to describe dirty code.
  8. 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
  9. Shy Code
  10. Error handling is ONE THING