SlideShare a Scribd company logo
1 of 29
Download to read offline
Clean code
Cleaner, cleaner, cleaner!
What is clean code?
Clean code
Clean code
Code example: product XML-feed parser
class FeedParser
{
public function doParse()
{
$products = array(); //array of products to return
$xml = simplexml_load_file("/tmp/products.xml"); //read xml file
if ($xml === FALSE) {
throw new Exception("feed not found"); //file not found
} else {
if (count($xml) === 0) {
throw new Exception("empty feed");
} else {
foreach($xml as $elem) {
$prod = $this->parse_elem($elem);
array_push($products, $prod); //add Product object
}
}
}
return $products;
}
(...)
Clean code
http://bit.ly/seminariUPCexample
class FeedParser
{
(...)
private function parse_elem($elem)
{
$name = $this->getElementErrorHandler($elem, "title");
$url = $this->getElementErrorHandler($elem, "link");
//Product not active
return new Product($name, $url, $elem->id, false);
}
private function getElementErrorHandler($elem, $attr) {
$item = (string)$elem->$attr;
if ($item == "") {
throw new Exception("incorrect item");
}
return $item;
}
}
● Code surface
○ Code style, DRY (duplication), comments
● Naming
● Easier functions
● Cleaner logic
○ Guards, configuration over hardcoding
Clean code
Index
Clean code
Code style: let’s find fails
class FeedParser
{
(...)
private function parse_elem($elem)
{
$name = $this->getElementErrorHandler($elem, "title");
$url = $this->getElementErrorHandler($elem, "link");
//Product not active
return new Product($name, $url, $elem->id, false);
}
private function getElementErrorHandler($elem, $attr) {
$item = (string)$elem->$attr;
if ($item == "") {
throw new Exception("incorrect item");
}
return $item;
}
}
● A repository with n developers should look homogeneous
● Code style (CS) tools
○ Verification
○ Automatic fixer
Clean code
Code style
● Impatient duplication
○ copy it and make a couple of changes
● Inter-developer duplication
○ Make it easy to use/reuse
Clean code
Don’t Repeat Yourself (DRY)
● Imposed duplication (unavoidable case)
○ Multiple representations of information
● Use a copy-paste detector
Clean code
Don’t Repeat Yourself (DRY)
● The less, the better!
● Usually comments are not needed
○ Redundant
○ Outdated
● Or even worse..
○ Commented out code
Clean code
Comments
Clean code
Any useful comment here?
class FeedParser
{
public function doParse()
{
$products = array(); //array of products to return
$xml = simplexml_load_file("/tmp/products.xml"); //read xml file
if ($xml === FALSE) {
throw new Exception("feed not found"); //file not found
} else {
if (count($xml) === 0) {
throw new Exception("empty feed");
} else {
foreach($xml as $elem) {
$prod = $this->parse_elem($elem);
array_push($products, $prod); //add Product object
}
}
}
return $products;
}
(...)
● Use the code itself to explain the logic
○ Use a variable instead of a comment
○ Use intention revealing names in vars and functions
Clean code
Comments
Clean code
Use a variable instead of a comment
private function parse_elem($elem)
{
$name = $this->getElementErrorHandler($elem, "title");
$url = $this->getElementErrorHandler($elem, "link");
//Product not active
return new Product($name, $url, $elem->id, false);
}
Clean code
Use a variable instead of a comment
private function parse_elem($elem)
{
$name = $this->getElementErrorHandler($elem, "title");
$url = $this->getElementErrorHandler($elem, "link");
//Product not active
return new Product($name, $url, $elem->id, false);
}
--------
private function parse_elem($elem)
{
$name = $this->getElementErrorHandler($elem, "title");
$url = $this->getElementErrorHandler($elem, "link");
$isActive = false;
return new Product($name, $url, $elem->id, $isActive);
}
● Intention-revealing names
○ int days; //days since last purchase
○ int daysSinceLastPurchase;
● Shared vocabulary with the team
● Precise vocabulary
○ No “manageUser(...)” but “updateUserContactInfo(...)”
○ No “killUserInDb()” but “deleteUserFromDb()”
Clean code
Naming
Clean code
Looking for meaningful names
private function parse_elem($elem)
{
$name = $this->getElementErrorHandler($elem, "title");
$url = $this->getElementErrorHandler($elem, "link");
$isActive = false;
return new Product($name, $url, $elem->id, $isActive);
}
Clean code
Looking for meaningful names
private function parse_elem($elem)
{
$name = $this->getElementErrorHandler($elem, "title");
$url = $this->getElementErrorHandler($elem, "link");
$isActive = false;
return new Product($name, $url, $elem->id, $isActive);
}
--------
private function createProductFromXmlData($productXmlData)
{
$name = $this->getAttribute($productXmlData, "title");
$url = $this->getAttribute($productXmlData, "link");
$isActive = false;
return new Product($name, $url, $productXmlData->id, $isActive);
}
● Small! Really small!
○ 2, 3, 4 lines
● Do ONLY one thing!
Clean code
Easier functions
Clean code
Does doParse() do only one thing?
public function doParse()
{
$products = array();
$xml = simplexml_load_file("/tmp/products.xml");
if ($xml === FALSE) {
throw new Exception("feed not found");
} else {
if (count($xml) === 0) {
throw new Exception("empty feed");
} else {
foreach($xml as $elem) {
$prod = $this->createProductFromXmlData($elem);
array_push($products, $prod);
}
}
}
return $products;
}
Clean code
public function doParse()
{
$xmlData = $this->readXML("/tmp/products.xml");
$products = $this->extractProductsFromXmlData($xmlData);
return $products;
}
private function readXML($filename)
{
$xmlData = simplexml_load_file($filename);
if ($xmlData === FALSE) {
throw new Exception("feed not found");
} elseif (count($xml) === 0) {
throw new Exception("empty feed");
}
return $xmlData;
}
private function extractProductsFromXmlData($xmlData)
{
$products = array();
foreach($xmlData as $productXml) {
$prod = $this->createProductFromXmlData($productXml);
array_push($products, $prod);
}
return $products;
}
● Keep same level of abstraction
○ From top to bottom, outside in
● Arguments
○ Avoid many arguments: use objects or DTOs instead
○ Caution with flags (bool arguments)
Clean code
Easier functions
Clean code
Avoiding flags, and keeping same level
private function createProductFromXmlData($productXmlData)
{
$name = $this->getAttribute($productXmlData, "title");
$url = $this->getAttribute($productXmlData, "link");
$isActive = false;
return new Product($name, $url, $productXmlData->id, $isActive);
}
Clean code
Avoiding flags, and keeping same level
private function createProductFromXmlData($productXmlData)
{
$name = $this->getAttribute($productXmlData, "title");
$url = $this->getAttribute($productXmlData, "link");
$isActive = false;
return new Product($name, $url, $productXmlData->id, $isActive);
}
private function createProductFromXmlData($productXmlData)
{
$name = $this->getAttribute($productXmlData, "title");
$url = $this->getAttribute($productXmlData, "link");
$id = $this->getAttribute($productXmlData, "id");
return new Product::createInactive($name, $url, $id);
}
● Guard clauses
● Configuration over hardcoding
Clean code
Cleaner logic
Clean code
private function readXML($filename)
{
$xmlData = simplexml_load_file($filename);
if ($xmlData === FALSE) {
throw new Exception("feed not found");
} elseif (count($xml) === 0) {
throw new Exception("empty feed");
}
return $xmlData;
}
// Let’s add guard clauses
Clean code
private function readXML($filename)
{
$xmlData = simplexml_load_file($filename);
if ($xmlData === FALSE) {
throw new Exception("feed not found");
} elseif (count($xml) === 0) {
throw new Exception("empty feed");
}
return $xmlData;
}
// Let’s add guard clauses
private function readXML($filename)
{
$this->checkFileExists($filename);
$xmlData = simplexml_load_file($filename);
$this->checkXmlHasContent($xmlData);
return $xmlData;
}
private function checkFileExists($filename)
{
if (!file_exists($filename)) {
throw new Exception("File $filename not found");
}
}
Clean code
class FeedParser
{
public function doParse()
{
$xmlData = $this->readXML("/tmp/products.xml");
$products = $this->extractProductsFromXmlData($xmlData);
return $products;
}
// Let’s remove the hardcoding
Clean code
class FeedParser
{
public function doParse()
{
$xmlData = $this->readXML("/tmp/products.xml");
$products = $this->extractProductsFromXmlData($xmlData);
return $products;
}
// Let’s remove the hardcoding
class FeedParser
{
public function __construct($filename)
{
$this->XmlFilename = $filename;
}
public function doParse()
{
$xmlData = $this->readXML($this->XmlFilename);
$products = $this->extractProductsFromXmlData($xmlData);
return $products;
}
● Books:
○ Clean Code (Robert “Uncle Bob” Martin)
○ The Pragmatic Programmer (Hunt & Tomas)
○ Refactoring (Fowler)
Clean code
And you can continue cleaning… forever

More Related Content

What's hot

PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5 Wildan Maulana
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHPGuilherme Blanco
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language TriviaNikita Popov
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML SchemaRaji Ghawi
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8XSolve
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 

What's hot (20)

PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
Oops in php
Oops in phpOops in php
Oops in php
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 

Viewers also liked

Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Professional development
Professional developmentProfessional development
Professional developmentJulio Martinez
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in SwiftDerek Lee Boire
 
clean code for high quality software
clean code for high quality softwareclean code for high quality software
clean code for high quality softwareArif Huda
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to DockerJulio Martinez
 
Conclusion of the Seminary UPC 2017
Conclusion of the Seminary UPC 2017Conclusion of the Seminary UPC 2017
Conclusion of the Seminary UPC 2017Julio Martinez
 
Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)jmiguel rodriguez
 
Introduction to hexagonal architecture
Introduction to hexagonal architectureIntroduction to hexagonal architecture
Introduction to hexagonal architectureManel Sellés
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
Practical OOP In Java
Practical OOP In JavaPractical OOP In Java
Practical OOP In Javawiradikusuma
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 

Viewers also liked (20)

Clean Code
Clean CodeClean Code
Clean Code
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Professional development
Professional developmentProfessional development
Professional development
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
 
clean code for high quality software
clean code for high quality softwareclean code for high quality software
clean code for high quality software
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
Conclusion of the Seminary UPC 2017
Conclusion of the Seminary UPC 2017Conclusion of the Seminary UPC 2017
Conclusion of the Seminary UPC 2017
 
Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)Clean Code (Presentacion interna en Virtual Software)
Clean Code (Presentacion interna en Virtual Software)
 
Clean code
Clean codeClean code
Clean code
 
Introduction to hexagonal architecture
Introduction to hexagonal architectureIntroduction to hexagonal architecture
Introduction to hexagonal architecture
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Clean Code
Clean CodeClean Code
Clean Code
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Practical OOP In Java
Practical OOP In JavaPractical OOP In Java
Practical OOP In Java
 
OOP java
OOP javaOOP java
OOP java
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 

Similar to Introduction to Clean Code

DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDrupalCamp Kyiv
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceIvan Chepurnyi
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docxwhitneyleman54422
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessorAlessandro Nadalin
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformanceJonas De Smet
 

Similar to Introduction to Clean Code (20)

Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEW
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docx
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessor
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 

Recently uploaded

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Recently uploaded (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

Introduction to Clean Code

  • 2. What is clean code? Clean code
  • 3. Clean code Code example: product XML-feed parser class FeedParser { public function doParse() { $products = array(); //array of products to return $xml = simplexml_load_file("/tmp/products.xml"); //read xml file if ($xml === FALSE) { throw new Exception("feed not found"); //file not found } else { if (count($xml) === 0) { throw new Exception("empty feed"); } else { foreach($xml as $elem) { $prod = $this->parse_elem($elem); array_push($products, $prod); //add Product object } } } return $products; } (...)
  • 4. Clean code http://bit.ly/seminariUPCexample class FeedParser { (...) private function parse_elem($elem) { $name = $this->getElementErrorHandler($elem, "title"); $url = $this->getElementErrorHandler($elem, "link"); //Product not active return new Product($name, $url, $elem->id, false); } private function getElementErrorHandler($elem, $attr) { $item = (string)$elem->$attr; if ($item == "") { throw new Exception("incorrect item"); } return $item; } }
  • 5. ● Code surface ○ Code style, DRY (duplication), comments ● Naming ● Easier functions ● Cleaner logic ○ Guards, configuration over hardcoding Clean code Index
  • 6. Clean code Code style: let’s find fails class FeedParser { (...) private function parse_elem($elem) { $name = $this->getElementErrorHandler($elem, "title"); $url = $this->getElementErrorHandler($elem, "link"); //Product not active return new Product($name, $url, $elem->id, false); } private function getElementErrorHandler($elem, $attr) { $item = (string)$elem->$attr; if ($item == "") { throw new Exception("incorrect item"); } return $item; } }
  • 7. ● A repository with n developers should look homogeneous ● Code style (CS) tools ○ Verification ○ Automatic fixer Clean code Code style
  • 8. ● Impatient duplication ○ copy it and make a couple of changes ● Inter-developer duplication ○ Make it easy to use/reuse Clean code Don’t Repeat Yourself (DRY)
  • 9. ● Imposed duplication (unavoidable case) ○ Multiple representations of information ● Use a copy-paste detector Clean code Don’t Repeat Yourself (DRY)
  • 10. ● The less, the better! ● Usually comments are not needed ○ Redundant ○ Outdated ● Or even worse.. ○ Commented out code Clean code Comments
  • 11. Clean code Any useful comment here? class FeedParser { public function doParse() { $products = array(); //array of products to return $xml = simplexml_load_file("/tmp/products.xml"); //read xml file if ($xml === FALSE) { throw new Exception("feed not found"); //file not found } else { if (count($xml) === 0) { throw new Exception("empty feed"); } else { foreach($xml as $elem) { $prod = $this->parse_elem($elem); array_push($products, $prod); //add Product object } } } return $products; } (...)
  • 12. ● Use the code itself to explain the logic ○ Use a variable instead of a comment ○ Use intention revealing names in vars and functions Clean code Comments
  • 13. Clean code Use a variable instead of a comment private function parse_elem($elem) { $name = $this->getElementErrorHandler($elem, "title"); $url = $this->getElementErrorHandler($elem, "link"); //Product not active return new Product($name, $url, $elem->id, false); }
  • 14. Clean code Use a variable instead of a comment private function parse_elem($elem) { $name = $this->getElementErrorHandler($elem, "title"); $url = $this->getElementErrorHandler($elem, "link"); //Product not active return new Product($name, $url, $elem->id, false); } -------- private function parse_elem($elem) { $name = $this->getElementErrorHandler($elem, "title"); $url = $this->getElementErrorHandler($elem, "link"); $isActive = false; return new Product($name, $url, $elem->id, $isActive); }
  • 15. ● Intention-revealing names ○ int days; //days since last purchase ○ int daysSinceLastPurchase; ● Shared vocabulary with the team ● Precise vocabulary ○ No “manageUser(...)” but “updateUserContactInfo(...)” ○ No “killUserInDb()” but “deleteUserFromDb()” Clean code Naming
  • 16. Clean code Looking for meaningful names private function parse_elem($elem) { $name = $this->getElementErrorHandler($elem, "title"); $url = $this->getElementErrorHandler($elem, "link"); $isActive = false; return new Product($name, $url, $elem->id, $isActive); }
  • 17. Clean code Looking for meaningful names private function parse_elem($elem) { $name = $this->getElementErrorHandler($elem, "title"); $url = $this->getElementErrorHandler($elem, "link"); $isActive = false; return new Product($name, $url, $elem->id, $isActive); } -------- private function createProductFromXmlData($productXmlData) { $name = $this->getAttribute($productXmlData, "title"); $url = $this->getAttribute($productXmlData, "link"); $isActive = false; return new Product($name, $url, $productXmlData->id, $isActive); }
  • 18. ● Small! Really small! ○ 2, 3, 4 lines ● Do ONLY one thing! Clean code Easier functions
  • 19. Clean code Does doParse() do only one thing? public function doParse() { $products = array(); $xml = simplexml_load_file("/tmp/products.xml"); if ($xml === FALSE) { throw new Exception("feed not found"); } else { if (count($xml) === 0) { throw new Exception("empty feed"); } else { foreach($xml as $elem) { $prod = $this->createProductFromXmlData($elem); array_push($products, $prod); } } } return $products; }
  • 20. Clean code public function doParse() { $xmlData = $this->readXML("/tmp/products.xml"); $products = $this->extractProductsFromXmlData($xmlData); return $products; } private function readXML($filename) { $xmlData = simplexml_load_file($filename); if ($xmlData === FALSE) { throw new Exception("feed not found"); } elseif (count($xml) === 0) { throw new Exception("empty feed"); } return $xmlData; } private function extractProductsFromXmlData($xmlData) { $products = array(); foreach($xmlData as $productXml) { $prod = $this->createProductFromXmlData($productXml); array_push($products, $prod); } return $products; }
  • 21. ● Keep same level of abstraction ○ From top to bottom, outside in ● Arguments ○ Avoid many arguments: use objects or DTOs instead ○ Caution with flags (bool arguments) Clean code Easier functions
  • 22. Clean code Avoiding flags, and keeping same level private function createProductFromXmlData($productXmlData) { $name = $this->getAttribute($productXmlData, "title"); $url = $this->getAttribute($productXmlData, "link"); $isActive = false; return new Product($name, $url, $productXmlData->id, $isActive); }
  • 23. Clean code Avoiding flags, and keeping same level private function createProductFromXmlData($productXmlData) { $name = $this->getAttribute($productXmlData, "title"); $url = $this->getAttribute($productXmlData, "link"); $isActive = false; return new Product($name, $url, $productXmlData->id, $isActive); } private function createProductFromXmlData($productXmlData) { $name = $this->getAttribute($productXmlData, "title"); $url = $this->getAttribute($productXmlData, "link"); $id = $this->getAttribute($productXmlData, "id"); return new Product::createInactive($name, $url, $id); }
  • 24. ● Guard clauses ● Configuration over hardcoding Clean code Cleaner logic
  • 25. Clean code private function readXML($filename) { $xmlData = simplexml_load_file($filename); if ($xmlData === FALSE) { throw new Exception("feed not found"); } elseif (count($xml) === 0) { throw new Exception("empty feed"); } return $xmlData; } // Let’s add guard clauses
  • 26. Clean code private function readXML($filename) { $xmlData = simplexml_load_file($filename); if ($xmlData === FALSE) { throw new Exception("feed not found"); } elseif (count($xml) === 0) { throw new Exception("empty feed"); } return $xmlData; } // Let’s add guard clauses private function readXML($filename) { $this->checkFileExists($filename); $xmlData = simplexml_load_file($filename); $this->checkXmlHasContent($xmlData); return $xmlData; } private function checkFileExists($filename) { if (!file_exists($filename)) { throw new Exception("File $filename not found"); } }
  • 27. Clean code class FeedParser { public function doParse() { $xmlData = $this->readXML("/tmp/products.xml"); $products = $this->extractProductsFromXmlData($xmlData); return $products; } // Let’s remove the hardcoding
  • 28. Clean code class FeedParser { public function doParse() { $xmlData = $this->readXML("/tmp/products.xml"); $products = $this->extractProductsFromXmlData($xmlData); return $products; } // Let’s remove the hardcoding class FeedParser { public function __construct($filename) { $this->XmlFilename = $filename; } public function doParse() { $xmlData = $this->readXML($this->XmlFilename); $products = $this->extractProductsFromXmlData($xmlData); return $products; }
  • 29. ● Books: ○ Clean Code (Robert “Uncle Bob” Martin) ○ The Pragmatic Programmer (Hunt & Tomas) ○ Refactoring (Fowler) Clean code And you can continue cleaning… forever