SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
clean code
breadcrumbs
Tech Lead at Compufácil compufacil.com.br
Github: jeanCarlomachado
Contributor of:
• Doctrine
• Zend Framework
• PHPmd
Twitter: JeanCarloMachad
Researching optimization based on nature inspirations
2
what clean code stands for?
Reader-focused development style
Produces software that’s easy to:
• write
• read
• maintain
Programming is the art of telling another human what one wants
the computer to do Donald Knuth
3
why it matters?
Broken windows theory
“All the rest of this code is crap, I’ll just follow suit.”
Software entropy, software rot.
4
why it matters?
Figure 1: Features over time considering design quality
5
the four characteristics of rotting software
• Rigidity
• Fragility
• Immobility
• Viscosity
6
rotting software 1 - rigidity
It’s hard to solve simple problems.
Estimating is hard.
7
rotting software 2 - fragility
The software breaks too often.
A change in one unrelated part breaks others.
Changes must be echoed in many places.
8
rotting software 3 - immobility
It’s the inability of reusing software from other places.
9
rotting software 4 - viscosity
It’s easier to go to the hacking mode than to the design preservation mode.
10
implications
• Software rot implies in frustrated developers
• Frustrated developers implies in more rotting
• Too much rooting implies in system rewrite
• Loss of money
• Loss of users
11
solution?
• Good practices
• Software craftsmanship
• Clean code skills
12
clean coder skills
Figure 2: clean-coder-skills.jpg
13
clean coder skills
Follow the ones what suites you most.
Relatively simple things can tolerate a certain level of disorganiza-
tion. However, as complexity increases, disorganization becomes sui-
cidal. Robert Martin
14
naming
Need to see the source for to know what a function does? Work on names!
Longer names are generally better than smaller one’s.
No And or Or in names.
15
comments
Usage scenarios
• Authors name
• Explain trade-offs of implementations
Avoid scenarios
• To express code
Inaccurate comments are way worse than no comments at all.
16
dry
Don’t Repeat Yourself
DRY on comments
/**
*
* @param $title The title of the CD
* @param $author The author of the CD
* @param $tracks The number of tracks of the CD
*
*/
public addCd($title, $author, int $tracks);
17
dry on documentation
Code and documentation are different views of the same model
Two places to edit models? DRY violation
Generate code from diagrams or diagrams from code
zendframework/ZendDeveloperTools
18
methods arguments
The ideal number of arguments of a method is ZERO.
More than tree is unacceptable.
Flags
public function useResultCache($bool, $lifetime = null/**...**
{
if ($bool) {
$this->setResultCacheLifetime($lifetime);
$this->setResultCacheId($resultCacheId);
return $this;
}
//...
}
19
classes - journal metaphor
Classes should be like journal articles.
In the header you get an general overview.
You are able to decide if you go further or not.
As you read down details increases.
20
objects vs data structures
Objects: hide data, expose operations over it
Data structures: expose data, no meaningful operation
21
kiss - keep it simple stupid
Related with few parts, few responsabilities, decoupling
Simplicity is different of easy
Easy is more related with your current understandings (relative)
There are systems which are easy but not simple
Over time simplicity pays off easiness
UNIX is very simple, it just needs a genius to understand it’s simplicity.
Dennis Ritchie
22
no magic
Before you commit to a framework, make sure you could write it
Simpler version
Some assembly
23
remove is better than adding
Don’t let existing code dictate future code
Be ready to refactor
Build a state of art namespace
24
tests
TDD is a design process
Prove the parts to prove the hole
Invert dependencies
Use gateways
What make testing harder is a bad in itself
Tests are the best documentation
test$method_$expectedResult_$conditions
25
law of demeter
Don’t play with your toy’s toys
If you need to change an object’s state, get the object to do it for you
Any method of an object should call only methods belonging to:
• itself;
• any parameters received;
• any objects it creates and any directly held component objects
26
composite reuse
One should build upon interfaces
OO languages replace function pointers with convenient polymor-
phism Robert C. Martin
Closure protocols and haskell type classe
Benefits
• Easier to maintain (no unexpected behaviors)
• Performance gain
• The inversion of source code and run time dependencies
27
many little classes vs few big ones
Any regular system will contain a vast quantity of logic
The same amount of business logic to care of
You prefer your tools being organized in boxes with little compartments and
good names?
Or only a compartment and all inside?
28
solid
Or the “first five principles” by Michael Feathers.
To make systems that are: is easy to maintain and extend over time
29
single responsibility principle (srp)
If you can think of more than one reason for changing a class, then that class
has more than one responsibility
<?php
interface UserInterface
{
public function setId($id);
public function getId();
public function setName($name);
public function getName();
public function findById($id);
public function insert();
public function update();
public function delete();
}
30
open close principle (oc)
The interface is closed to modification and new implementation implement
that interface
Rectangle, Square
Relates to composite reuse
31
liskov substitution (ls)
It’s possible to change subclasses without breaking the program
Usually instanceof is a sign of code smell
32
interface segregation principle (isp)
It’s better more interfaces than less
Clients should not be forced to depend upon interfaces that they don’t use
abstract class AbstractPostgreSQLDriver implements
Driver,
ExceptionConverterDriver,
VersionAwarePlatformDriver
33
dependency inversion
One should depend only on abstractions.
For PHP:
• https://github.com/container-interop/container-interop
• https://github.com/auraphp/Aura.Di
• https://github.com/zendframework/zend-servicemanager
34
object calisthenics
Seven code qualities premisses:
• Cohesion
• Loose coupling
• No redundancy
• Encapsulation
• Testability
• Readability
• Focus
35
1 - one level of indentation per method
Benefits
Finding bugs is much easier
If you have more than one indentation level you have more than one abstrac-
tion level
36
2 - don’t use else keyword
Else’s encourages the inclusion of more intermediate if’s
When possible avoid even if’s
Use polymorphism instead
37
3 - wrap all primitives and strings
Small objects make programs more maintainable
They serves as a container for logic that otherwise would be sparse
38
4 - first class collections
Any class with a collection shouldn’t contain other member variables
39
5 - one dot per line
Bad:
this->myMemberObject
->myMemberObjectMemberObject
->doFoo();
Good:
this->myMemberObjectMemberObject
->functionThatDoFooToo();
Relates to Law of Demeter
40
6 - don’t abbreviate
Abbreviation because of exhaustive use?
DRY violation
Too long names?
Maybe a SRP problem
41
7 - keep all entities small
No classes over 50 lines and no packages over 10 files
42
8 - no classes with more than two instance variables
Figure 3: Instance variables
43
9 - no getters/setters/properties
Encapsulate everything
Make objects change dependencies by themselves
Invert Dependencies
44
tools
• Codacy: https://www.codacy.com/
• https://github.com/adoy/vim-php-refactoring-toolbox
• https://github.com/object-calisthenics/
phpcs-calisthenics-rules
Style Guides
• PSR2
• Zend
• Symphony
45
more?
• Orthogonality
• Don’t return nulls
• Metrics
• Code Review
• Error Handling
Much more.
46
literature
1. Clean code: A hand book of Agile Software craftsmanship; Robert C.
Martin
2. The pragmatical programmer; Andrew Hunt
3. Code Complete; Steve McConnell
4. Refactoring: Improving the Design of Existing Code;
5. Release It!: Design and Deploy Production-Ready Software; Michael T.
Nygard
Those who do not remember the past are condemned to repeat it.
Jorge Agustin Nicolas Ruiz de Santayana y Borras
47
conclusion
Quality is a team issue. Andy hunt.
Teams as a hole should not tolerate broken windows.
Clean code is not about perfection.. It’s about honesty.
We made our best to leave the camp cleaner than we find it?
48
conclusion
But if we aim for the 80% where code needs the most. We are good enough.
Parts not critical to performance must be clean - not optimized.
The best programmers are 28 times best than the worst ones. Robert
Glass, Facts and Fallacies of Software Engineering
There’s always room for improvement.
49
questions?
Contact info
E-mail: contato@jeancarlomachado.com.br
IRC: JeanCarloMachado
50
thanks

Contenu connexe

Tendances

Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
Theo Jungeblut
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
Edorian
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
Lim Chanmann
 

Tendances (20)

Tdd
TddTdd
Tdd
 
Euro python 2015 writing quality code
Euro python 2015   writing quality codeEuro python 2015   writing quality code
Euro python 2015 writing quality code
 
Cross Compiling for Perl Hackers
Cross Compiling for Perl HackersCross Compiling for Perl Hackers
Cross Compiling for Perl Hackers
 
Tdd com Java
Tdd com JavaTdd com Java
Tdd com Java
 
TDD = bra design?
TDD = bra design?TDD = bra design?
TDD = bra design?
 
Coding standard
Coding standardCoding standard
Coding standard
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
 
Test driven development(tdd)
Test driven development(tdd)Test driven development(tdd)
Test driven development(tdd)
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
Tools for the Toolmakers
Tools for the ToolmakersTools for the Toolmakers
Tools for the Toolmakers
 
Coding standards
Coding standardsCoding standards
Coding standards
 
Tdd
TddTdd
Tdd
 
Python - code quality and production monitoring
Python - code quality and production monitoringPython - code quality and production monitoring
Python - code quality and production monitoring
 
Coding standard
Coding standardCoding standard
Coding standard
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
 
Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)
Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)
Partitioning Composite Code Changes to Facilitate Code Review (MSR2015)
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Importance of the quality of code
Importance of the quality of codeImportance of the quality of code
Importance of the quality of code
 
Static Code Analysis and AutoLint
Static Code Analysis and AutoLintStatic Code Analysis and AutoLint
Static Code Analysis and AutoLint
 

En vedette

Gaurav Kumar Resume
Gaurav Kumar ResumeGaurav Kumar Resume
Gaurav Kumar Resume
Gaurav kumar
 
Spain 7 Getting Started
Spain 7 Getting StartedSpain 7 Getting Started
Spain 7 Getting Started
SUDIPTO BOSE
 
Radisys Optimizing VAS for Greater Revenue Generation
Radisys Optimizing VAS for Greater Revenue GenerationRadisys Optimizing VAS for Greater Revenue Generation
Radisys Optimizing VAS for Greater Revenue Generation
Radisys Corporation
 
The munoz migration - geography family tree1
The munoz migration - geography family tree1The munoz migration - geography family tree1
The munoz migration - geography family tree1
pmunoz01
 
Unified Security Plugin for Opendaylight Controller
Unified Security Plugin for Opendaylight ControllerUnified Security Plugin for Opendaylight Controller
Unified Security Plugin for Opendaylight Controller
Saikat Chaudhuri
 
Hyper-V Disaster Recovery Optimizing
Hyper-V Disaster Recovery OptimizingHyper-V Disaster Recovery Optimizing
Hyper-V Disaster Recovery Optimizing
Ahmad Firdaus
 

En vedette (20)

Gaurav Kumar Resume
Gaurav Kumar ResumeGaurav Kumar Resume
Gaurav Kumar Resume
 
Spain 7 Getting Started
Spain 7 Getting StartedSpain 7 Getting Started
Spain 7 Getting Started
 
Radisys Optimizing VAS for Greater Revenue Generation
Radisys Optimizing VAS for Greater Revenue GenerationRadisys Optimizing VAS for Greater Revenue Generation
Radisys Optimizing VAS for Greater Revenue Generation
 
NREF Annual Report
NREF Annual ReportNREF Annual Report
NREF Annual Report
 
Rrgreenhandslof
RrgreenhandslofRrgreenhandslof
Rrgreenhandslof
 
The munoz migration - geography family tree1
The munoz migration - geography family tree1The munoz migration - geography family tree1
The munoz migration - geography family tree1
 
Coal mines bill, 2015, India
Coal mines bill, 2015, IndiaCoal mines bill, 2015, India
Coal mines bill, 2015, India
 
GBNews_DEC09
GBNews_DEC09GBNews_DEC09
GBNews_DEC09
 
GetBetter
GetBetterGetBetter
GetBetter
 
The Creditsafe Commercial Credit Managment Suite
The Creditsafe Commercial Credit Managment Suite The Creditsafe Commercial Credit Managment Suite
The Creditsafe Commercial Credit Managment Suite
 
Wb engineering
Wb engineeringWb engineering
Wb engineering
 
IBM X Force threat intelligence quarterly 1Q 2014
IBM X Force threat intelligence quarterly 1Q 2014IBM X Force threat intelligence quarterly 1Q 2014
IBM X Force threat intelligence quarterly 1Q 2014
 
ICMA Quarterly Report - FIRST QUARTER 2014
ICMA Quarterly Report - FIRST QUARTER 2014ICMA Quarterly Report - FIRST QUARTER 2014
ICMA Quarterly Report - FIRST QUARTER 2014
 
IT Next January 2010 Issue
IT Next January 2010 IssueIT Next January 2010 Issue
IT Next January 2010 Issue
 
Unified Security Plugin for Opendaylight Controller
Unified Security Plugin for Opendaylight ControllerUnified Security Plugin for Opendaylight Controller
Unified Security Plugin for Opendaylight Controller
 
Hyper-V Disaster Recovery Optimizing
Hyper-V Disaster Recovery OptimizingHyper-V Disaster Recovery Optimizing
Hyper-V Disaster Recovery Optimizing
 
SeGW Whitepaper from Radisys
SeGW Whitepaper from RadisysSeGW Whitepaper from Radisys
SeGW Whitepaper from Radisys
 
EdgeBuilder : Overview
EdgeBuilder : OverviewEdgeBuilder : Overview
EdgeBuilder : Overview
 
Kofax Virtual Hospital
Kofax Virtual HospitalKofax Virtual Hospital
Kofax Virtual Hospital
 
Training & Development at Jindal SAW Ltd
Training & Development at Jindal SAW LtdTraining & Development at Jindal SAW Ltd
Training & Development at Jindal SAW Ltd
 

Similaire à Clean Code V2

20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
Antonio de la Torre Fernández
 
RedisConf18 - Implementing a New Data Structure for Redis
RedisConf18 - Implementing a New Data Structure for Redis  RedisConf18 - Implementing a New Data Structure for Redis
RedisConf18 - Implementing a New Data Structure for Redis
Redis Labs
 

Similaire à Clean Code V2 (20)

20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
 
Writing code for people
Writing code for peopleWriting code for people
Writing code for people
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Wood
 
Clean Infrastructure as Code
Clean Infrastructure as CodeClean Infrastructure as Code
Clean Infrastructure as Code
 
More about PHP
More about PHPMore about PHP
More about PHP
 
Zend Di in ZF 2.0
Zend Di in ZF 2.0Zend Di in ZF 2.0
Zend Di in ZF 2.0
 
10 Ways To Improve Your Code
10 Ways To Improve Your Code10 Ways To Improve Your Code
10 Ways To Improve Your Code
 
Quick Intro to Clean Coding
Quick Intro to Clean CodingQuick Intro to Clean Coding
Quick Intro to Clean Coding
 
RedisConf18 - Implementing a New Data Structure for Redis
RedisConf18 - Implementing a New Data Structure for Redis  RedisConf18 - Implementing a New Data Structure for Redis
RedisConf18 - Implementing a New Data Structure for Redis
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
 
Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Code Quality
Code QualityCode Quality
Code Quality
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad Wood
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
Code quality
Code qualityCode quality
Code quality
 
Tool up your lamp stack
Tool up your lamp stackTool up your lamp stack
Tool up your lamp stack
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 

Plus de Jean Carlo Machado

Plus de Jean Carlo Machado (11)

Python clean code for data producs
Python clean code for data producsPython clean code for data producs
Python clean code for data producs
 
Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python
 
Search microservice
Search microserviceSearch microservice
Search microservice
 
Git avançado
Git avançadoGit avançado
Git avançado
 
Functional php
Functional phpFunctional php
Functional php
 
Why functional programming matters
Why functional programming mattersWhy functional programming matters
Why functional programming matters
 
Clean code v3
Clean code v3Clean code v3
Clean code v3
 
Review articles bio inspired algorithms
Review articles bio inspired algorithmsReview articles bio inspired algorithms
Review articles bio inspired algorithms
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Limitações do HTML no Desenvolvimento de Jogos Multiplataforma
Limitações do HTML no Desenvolvimento de Jogos MultiplataformaLimitações do HTML no Desenvolvimento de Jogos Multiplataforma
Limitações do HTML no Desenvolvimento de Jogos Multiplataforma
 
Clean code
Clean codeClean code
Clean code
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Clean Code V2

  • 2. breadcrumbs Tech Lead at Compufácil compufacil.com.br Github: jeanCarlomachado Contributor of: • Doctrine • Zend Framework • PHPmd Twitter: JeanCarloMachad Researching optimization based on nature inspirations 2
  • 3. what clean code stands for? Reader-focused development style Produces software that’s easy to: • write • read • maintain Programming is the art of telling another human what one wants the computer to do Donald Knuth 3
  • 4. why it matters? Broken windows theory “All the rest of this code is crap, I’ll just follow suit.” Software entropy, software rot. 4
  • 5. why it matters? Figure 1: Features over time considering design quality 5
  • 6. the four characteristics of rotting software • Rigidity • Fragility • Immobility • Viscosity 6
  • 7. rotting software 1 - rigidity It’s hard to solve simple problems. Estimating is hard. 7
  • 8. rotting software 2 - fragility The software breaks too often. A change in one unrelated part breaks others. Changes must be echoed in many places. 8
  • 9. rotting software 3 - immobility It’s the inability of reusing software from other places. 9
  • 10. rotting software 4 - viscosity It’s easier to go to the hacking mode than to the design preservation mode. 10
  • 11. implications • Software rot implies in frustrated developers • Frustrated developers implies in more rotting • Too much rooting implies in system rewrite • Loss of money • Loss of users 11
  • 12. solution? • Good practices • Software craftsmanship • Clean code skills 12
  • 13. clean coder skills Figure 2: clean-coder-skills.jpg 13
  • 14. clean coder skills Follow the ones what suites you most. Relatively simple things can tolerate a certain level of disorganiza- tion. However, as complexity increases, disorganization becomes sui- cidal. Robert Martin 14
  • 15. naming Need to see the source for to know what a function does? Work on names! Longer names are generally better than smaller one’s. No And or Or in names. 15
  • 16. comments Usage scenarios • Authors name • Explain trade-offs of implementations Avoid scenarios • To express code Inaccurate comments are way worse than no comments at all. 16
  • 17. dry Don’t Repeat Yourself DRY on comments /** * * @param $title The title of the CD * @param $author The author of the CD * @param $tracks The number of tracks of the CD * */ public addCd($title, $author, int $tracks); 17
  • 18. dry on documentation Code and documentation are different views of the same model Two places to edit models? DRY violation Generate code from diagrams or diagrams from code zendframework/ZendDeveloperTools 18
  • 19. methods arguments The ideal number of arguments of a method is ZERO. More than tree is unacceptable. Flags public function useResultCache($bool, $lifetime = null/**...** { if ($bool) { $this->setResultCacheLifetime($lifetime); $this->setResultCacheId($resultCacheId); return $this; } //... } 19
  • 20. classes - journal metaphor Classes should be like journal articles. In the header you get an general overview. You are able to decide if you go further or not. As you read down details increases. 20
  • 21. objects vs data structures Objects: hide data, expose operations over it Data structures: expose data, no meaningful operation 21
  • 22. kiss - keep it simple stupid Related with few parts, few responsabilities, decoupling Simplicity is different of easy Easy is more related with your current understandings (relative) There are systems which are easy but not simple Over time simplicity pays off easiness UNIX is very simple, it just needs a genius to understand it’s simplicity. Dennis Ritchie 22
  • 23. no magic Before you commit to a framework, make sure you could write it Simpler version Some assembly 23
  • 24. remove is better than adding Don’t let existing code dictate future code Be ready to refactor Build a state of art namespace 24
  • 25. tests TDD is a design process Prove the parts to prove the hole Invert dependencies Use gateways What make testing harder is a bad in itself Tests are the best documentation test$method_$expectedResult_$conditions 25
  • 26. law of demeter Don’t play with your toy’s toys If you need to change an object’s state, get the object to do it for you Any method of an object should call only methods belonging to: • itself; • any parameters received; • any objects it creates and any directly held component objects 26
  • 27. composite reuse One should build upon interfaces OO languages replace function pointers with convenient polymor- phism Robert C. Martin Closure protocols and haskell type classe Benefits • Easier to maintain (no unexpected behaviors) • Performance gain • The inversion of source code and run time dependencies 27
  • 28. many little classes vs few big ones Any regular system will contain a vast quantity of logic The same amount of business logic to care of You prefer your tools being organized in boxes with little compartments and good names? Or only a compartment and all inside? 28
  • 29. solid Or the “first five principles” by Michael Feathers. To make systems that are: is easy to maintain and extend over time 29
  • 30. single responsibility principle (srp) If you can think of more than one reason for changing a class, then that class has more than one responsibility <?php interface UserInterface { public function setId($id); public function getId(); public function setName($name); public function getName(); public function findById($id); public function insert(); public function update(); public function delete(); } 30
  • 31. open close principle (oc) The interface is closed to modification and new implementation implement that interface Rectangle, Square Relates to composite reuse 31
  • 32. liskov substitution (ls) It’s possible to change subclasses without breaking the program Usually instanceof is a sign of code smell 32
  • 33. interface segregation principle (isp) It’s better more interfaces than less Clients should not be forced to depend upon interfaces that they don’t use abstract class AbstractPostgreSQLDriver implements Driver, ExceptionConverterDriver, VersionAwarePlatformDriver 33
  • 34. dependency inversion One should depend only on abstractions. For PHP: • https://github.com/container-interop/container-interop • https://github.com/auraphp/Aura.Di • https://github.com/zendframework/zend-servicemanager 34
  • 35. object calisthenics Seven code qualities premisses: • Cohesion • Loose coupling • No redundancy • Encapsulation • Testability • Readability • Focus 35
  • 36. 1 - one level of indentation per method Benefits Finding bugs is much easier If you have more than one indentation level you have more than one abstrac- tion level 36
  • 37. 2 - don’t use else keyword Else’s encourages the inclusion of more intermediate if’s When possible avoid even if’s Use polymorphism instead 37
  • 38. 3 - wrap all primitives and strings Small objects make programs more maintainable They serves as a container for logic that otherwise would be sparse 38
  • 39. 4 - first class collections Any class with a collection shouldn’t contain other member variables 39
  • 40. 5 - one dot per line Bad: this->myMemberObject ->myMemberObjectMemberObject ->doFoo(); Good: this->myMemberObjectMemberObject ->functionThatDoFooToo(); Relates to Law of Demeter 40
  • 41. 6 - don’t abbreviate Abbreviation because of exhaustive use? DRY violation Too long names? Maybe a SRP problem 41
  • 42. 7 - keep all entities small No classes over 50 lines and no packages over 10 files 42
  • 43. 8 - no classes with more than two instance variables Figure 3: Instance variables 43
  • 44. 9 - no getters/setters/properties Encapsulate everything Make objects change dependencies by themselves Invert Dependencies 44
  • 45. tools • Codacy: https://www.codacy.com/ • https://github.com/adoy/vim-php-refactoring-toolbox • https://github.com/object-calisthenics/ phpcs-calisthenics-rules Style Guides • PSR2 • Zend • Symphony 45
  • 46. more? • Orthogonality • Don’t return nulls • Metrics • Code Review • Error Handling Much more. 46
  • 47. literature 1. Clean code: A hand book of Agile Software craftsmanship; Robert C. Martin 2. The pragmatical programmer; Andrew Hunt 3. Code Complete; Steve McConnell 4. Refactoring: Improving the Design of Existing Code; 5. Release It!: Design and Deploy Production-Ready Software; Michael T. Nygard Those who do not remember the past are condemned to repeat it. Jorge Agustin Nicolas Ruiz de Santayana y Borras 47
  • 48. conclusion Quality is a team issue. Andy hunt. Teams as a hole should not tolerate broken windows. Clean code is not about perfection.. It’s about honesty. We made our best to leave the camp cleaner than we find it? 48
  • 49. conclusion But if we aim for the 80% where code needs the most. We are good enough. Parts not critical to performance must be clean - not optimized. The best programmers are 28 times best than the worst ones. Robert Glass, Facts and Fallacies of Software Engineering There’s always room for improvement. 49