SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programmingMahmoud Masih Tehrani
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScriptpcnmtutorials
 
Javascript conditional statements
Javascript conditional statementsJavascript conditional statements
Javascript conditional statementsnobel mujuji
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code PrinciplesYeurDreamin'
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsGanesh Samarthyam
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 

Tendances (20)

Clean code
Clean codeClean code
Clean code
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
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
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Selenium Locators
Selenium LocatorsSelenium Locators
Selenium Locators
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
Javascript conditional statements
Javascript conditional statementsJavascript conditional statements
Javascript conditional statements
 
Junit
JunitJunit
Junit
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 

Similaire à 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
 

Similaire à 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
 

Dernier

Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 

Dernier (20)

Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.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:

Notes de l'éditeur

  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