SlideShare una empresa de Scribd logo
1 de 37
Descargar para leer sin conexión
Pascal Larocque
● TrustCharge Team
● Behat guy
● Testing guy
● SOLID guy
● Pattern guy
● Father of 3
● Star Wars Geek
@pascallarocque
Bad Code
● Singletons
● Tight Coupling
● Untestable
● Premature Optimization
● Indescriptive name
● Duplication
Cost of Bad Code
● Very hard / Impossible to estimate
● Slows down team velocity
● High Learning curve
● Brings down team moral
● Increases cost of development
The Primal Conundrum
Programmers face a conundrum of basic
values. All developers with more than a few
years experience know that previous messes
slow them down. And yet all developers feel the
pressure to make messes in order to meet
deadlines. In short, they don’t take the time to
go fast!
True professionals know that the second part of
the conundrum is wrong. You will not make the
deadline by making the mess. Indeed, the
mess will slow you down instantly, and will
force you to miss the deadline. The only way to
make the deadline—the only way to go fast—is
to keep the code as clean as possible at all
times.
How do I write Clean Code?
What is Clean Code?
“Clean code can be read, and enhanced by a
developer other than its original author. It has
unit and acceptance tests. It has meaningful
names. It provides one way rather than many
ways for doing one thing. It has minimal
dependencies, which are explicitly defined,
and provides a clear and minimal API. Code
should be literate since depending on the
language, not all necessary information can be
expressed clearly in code alone.”
- Dave Thomas
“Clean code is simple and direct. Clean code reads
like well-written prose. Clean code never obscures
the designer’s intent but rather is full of crisp
abstractions and straightforward lines of control.”
- Grady Booch
“I like my code to be elegant and efficient. The logic
should be straightforward to make it hard for bugs to
hide, the dependencies minimal to ease maintenance,
error handling complete according to an articulated
strategy, and performance close to optimal so as not to
tempt people to make the code messy with unprincipled
optimizations. Clean code does one thing well.”
- Bjarne Stroustrup
You know you are working on clean code
when each routine you read turns out to be
pretty much what you expected. You can call it
beautiful code when the code also makes it
look like the language was made for the
problem.
- Ward Cunningham
What is Clean Code?
The Boy Scout Rule
“Leave the campground cleaner than you found it”
Code Rots and Degrades as time passes
The Code has to be kept clean over time. We
must take an active role in preventing the
degradation.
Naming
● Use intention revealing names
○ Why it exists
○ What it does
○ How it’s used
● Classes should have nouns or noun phrases
○ Don’t use Manager, Processor, Data or Info
● Methods should have verbs or verb phrases
● Accessor, Mutators or predicates should
have get, set or is
● Use solution domain name
○ Factory, Visitor, Queue
Functions
● Small
● Smaller than that!!!
● Does ONE THING
● Does ONLY ONE THING
● Blocks and Indentation
○ IF, While, For
● One level of abstraction per function
○ getHTML()
○ $parsed = Parser::render($url)
○ $xml->append($node)
Functions
● Reads like a Top Down Narrative
○ To render the page we get all the content
○ To get all the content we extract it from the DB
○ To extract it from the DB we need to connect
Function Arguments
The ideal number of arguments for a function is
zero (niladic).
Next comes one (monadic), followed closely by
two (dyadic).
Three arguments (triadic) should be avoided
where possible.
More than three (polyadic) requires very special
justification—and then shouldn’t be used
anyway.
Function Arguments - Flags
Flag Arguments should
be avoided.
It does 1 thing if true
and another thing when
it’s false.
render(true):
renderForScreen()
renderForTest()
Function Argument - Objects
It’s easier to pass Objects instead of a long
argument list or array
Rectangle makeRectangle(Double x1, Double y1, Double x2, Double y2)
Rectangle makeRectangle(Point point1, Point point2)
checkPassword(username, password) {
user = $this->dataAccessor->findByUsername
(username)
valid= md5($user->getPassword()) === password
if(valid) {
Session.init(user)
} else {
Session.clear()
}
return valid
}
Have no side effect
Sides effects are lies.
BAD
Enforce Temporal Coupling
class ACL {
function login(username, password) {
this->user = this->findUser(username, password)
this->getPermissions()
this->startACLSession()
}
}
BAD
class ACL {
function login(username, password) {
this->user = this->findUser(username, password)
this->permissions = this->getPermissions($this->user)
this->startACLSession(this->permissions)
}
}
BETTER
if ($this->_sortBySet() === true) {
...
} else if ($this->_sortByActor() === true) {
...
} else if ($this->_sortByClip() === true) {
...
} else {
…
}
Make Conditions clear
if (true === $bySetId && (true === empty($photoCollection) || true === empty($photoSet))) {
...
} else if (true === $byActorId && (true === empty($photoCollection) || true === empty($actor))) {
...
} else if (true === $byClipId && (true === empty($photoCollection) || true === empty($scene))) {
...
} else {
…
}
BAD
BETTER
sortingAlgorithmInterface = phosetSortingFactory->findSorter(sortBy)
sorted list = sortingAlgorithmInterface ->sort(photosetList)
Replace Conditions with Factory
if ($this->_sortBySet() === true) {
...
} else if ($this->_sortByActor() === true {
...
} else if ($this->_sortByClip() === true) {
...
} else {
…
}
POLYMORPHISM
GOODNESS
Abstract Factory Pattern
Encapsulate Change
Class UserRepository {
function findById(id) {
return Doctrine::getTable('Users')->createQuery(‘u’)
->where(‘u.id = ?’, id)
->fetchOne();
}
}
ORM
MY
GOD
Class UserRepository {
function findById(id) {
userData = this->dataAccessor->findById(id)
user = userFactory->create(userData)
return user
}
}
The only constant is Change.
Strategy Pattern
The Law of Demeter
method f of a class C should only call the
methods of these:
● C
● An object created by f
● An object passed as an argument to f
● An object held in an instance variable of C
Class ACL {
protected user
function hasAccessToAdmin() {
return this->user ->isAdmin()
}
}
The Law of Demeter
Class ACL {
function hasAccessToAdmin() {
return getUserManager()
->getUser(123)
->getProfile()
->isAdmin()
}
}
BAD
Class ACL {
protected user
protected aclVisitor
function setVisitor(visitor) { … }
function hasAccessToAdmin() {
return this->aclVisitor
->isAdmin(this->user-getProfile())
}
}
Class AclVisitor {
function isAdmin(profile) {
return profile->isadmin()
}
}
MEH
PATTERNS!!!
Visitor Pattern
Don’t pass NULL, Don’t return NULL
Throw an exception
Return a NullObject
findUser(ID) {
user = this->dataAccessor->findById(ID)
if(user == null) {
user = new NullUser();
}
return user
}
Class NullUser {
function getName { return ‘’ //DO NOTHING }
}
NullObject Pattern
Observer Pattern
Singleton Pattern
Singleton Pattern
"Singletons are the path of the dark side.
Singletons lead to implicit dependencies.
Implicit dependencies lead to global state.
Global state leads to suffering."
As events arrive from the outside world at a port, a
technology-specific adapter converts it into a usable
procedure call or message and passes it to the application.
CreditCardService
Hexagonal Architecture
CreditCardService
HTTP
REST
PHPUnit
SOCKET ADAPTER
When the application has something to send out, it sends it out through a port
to an adapter, which creates the appropriate signals needed by the receiving
technology (human or automated).
CreditCardService
Hexagonal Architecture
CreditCardService
HTML
XML
PHPUnit
JSONP
ADAPTER
Class CreditCardService
__construct(InputInterface, OutputInterface) {
this->input = InputInterface
this->output = OutputInterface
}
function process() {
input = this->input->getInput()
output = this->doProcessing(input)
return this->ouput
->sendOutput(output)
}
}
CreditCardService
Hexagonal Architecture
CreditCardService
class CreditCardHTTPInputAdapter implements
InputInterface{
function getInput() {..}
}
class CreditCardJSONPOutputAdapter
implements OutputInterface{
function sendOutput(output) {..}
}
More stuff
Command Query Separation
Functions should either do something or answer something, but not both.
DRY
Don’t repeat yourself. Duplication may be the root of all evil in software.
SOLID
Single Responsibility, Open/Closed Principle, Liskov substitution principle,
Interface segregation, Dependency Inversion
Structured Programming
Every function and every block has one Entry and one Exit
Use Exceptions and Error Handling
Functions should do one thing. Error handling is one thing. Thus, a function that
handles errors should do nothing else.
SHARE KNOWLEDGE
KNOWLEDGE DECAYS FAST
SLOW DOWN TO GO FAST
NEVER ASK PERMISSION TO DO YOUR
JOB CORRECTLY
QUESTIONS?

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Java exception
Java exception Java exception
Java exception
 
Process management
Process managementProcess management
Process management
 
Code refactoring
Code refactoringCode refactoring
Code refactoring
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring Techniques
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
Component based software engineering
Component based software engineeringComponent based software engineering
Component based software engineering
 
Clean code
Clean code Clean code
Clean code
 
Introduction to Robot Framework
Introduction to Robot FrameworkIntroduction to Robot Framework
Introduction to Robot Framework
 
Unified process Model
Unified process ModelUnified process Model
Unified process Model
 
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
 
Quality Management in Software Engineering SE24
Quality Management in Software Engineering SE24Quality Management in Software Engineering SE24
Quality Management in Software Engineering SE24
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
testng
testngtestng
testng
 
Selenium
SeleniumSelenium
Selenium
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Ef code first
Ef code firstEf code first
Ef code first
 

Destacado

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 CampTheo Jungeblut
 
Kata - Java - Tests - JUnit 4
Kata - Java - Tests - JUnit 4Kata - Java - Tests - JUnit 4
Kata - Java - Tests - JUnit 4kaftanenko
 
SOLID and Clean Code with life project example
SOLID and Clean Code with life project exampleSOLID and Clean Code with life project example
SOLID and Clean Code with life project examplevasya_bh
 
Agile! Welche Rolle spielt das Management
Agile! Welche Rolle spielt das ManagementAgile! Welche Rolle spielt das Management
Agile! Welche Rolle spielt das ManagementMischa Ramseyer
 
Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)Rodrigo Kono
 
História do linux ppt
História do linux pptHistória do linux ppt
História do linux pptshade09
 
How To Draw A Boy The Easy Way
How To Draw A Boy The Easy WayHow To Draw A Boy The Easy Way
How To Draw A Boy The Easy WayIrvine Blue
 
How to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slidesHow to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slidesotikik
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShareSlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Destacado (14)

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
 
Kata - Java - Tests - JUnit 4
Kata - Java - Tests - JUnit 4Kata - Java - Tests - JUnit 4
Kata - Java - Tests - JUnit 4
 
SOLID and Clean Code with life project example
SOLID and Clean Code with life project exampleSOLID and Clean Code with life project example
SOLID and Clean Code with life project example
 
Clean Code
Clean CodeClean Code
Clean Code
 
Agile! Welche Rolle spielt das Management
Agile! Welche Rolle spielt das ManagementAgile! Welche Rolle spielt das Management
Agile! Welche Rolle spielt das Management
 
Conhecendo Melhor O Linux
Conhecendo Melhor O LinuxConhecendo Melhor O Linux
Conhecendo Melhor O Linux
 
Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)Boas práticas técnica para um código limpo (Clean Code)
Boas práticas técnica para um código limpo (Clean Code)
 
História do linux ppt
História do linux pptHistória do linux ppt
História do linux ppt
 
How To Draw A Boy The Easy Way
How To Draw A Boy The Easy WayHow To Draw A Boy The Easy Way
How To Draw A Boy The Easy Way
 
How to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slidesHow to make Awesome Diagrams for your slides
How to make Awesome Diagrams for your slides
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar a Clean code & design patterns

Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?Aleksandr Yampolskiy
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Fwdays
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Alberto Naranjo
 
Clean Code JavaScript
Clean Code JavaScriptClean Code JavaScript
Clean Code JavaScriptRiza Fahmi
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suckRoss Bruniges
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rockmartincronje
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
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 WoodOrtus Solutions, Corp
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
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 WoodOrtus Solutions, Corp
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringCary Millsap
 

Similar a Clean code & design patterns (20)

Clean code
Clean codeClean code
Clean code
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?Much ado about randomness. What is really a random number?
Much ado about randomness. What is really a random number?
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Clean code
Clean codeClean code
Clean code
 
Clean Code JavaScript
Clean Code JavaScriptClean Code JavaScript
Clean Code JavaScript
 
Good++
Good++Good++
Good++
 
Writing JavaScript that doesn't suck
Writing JavaScript that doesn't suckWriting JavaScript that doesn't suck
Writing JavaScript that doesn't suck
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
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
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Responsible JavaScript
Responsible JavaScriptResponsible JavaScript
Responsible JavaScript
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
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
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and Monitoring
 

Último

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
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...Miguel Araújo
 
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 challengesrafiqahmad00786416
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
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 REVIEWERMadyBayot
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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, Adobeapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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...
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Clean code & design patterns

  • 1.
  • 2. Pascal Larocque ● TrustCharge Team ● Behat guy ● Testing guy ● SOLID guy ● Pattern guy ● Father of 3 ● Star Wars Geek @pascallarocque
  • 3. Bad Code ● Singletons ● Tight Coupling ● Untestable ● Premature Optimization ● Indescriptive name ● Duplication
  • 4. Cost of Bad Code ● Very hard / Impossible to estimate ● Slows down team velocity ● High Learning curve ● Brings down team moral ● Increases cost of development
  • 5. The Primal Conundrum Programmers face a conundrum of basic values. All developers with more than a few years experience know that previous messes slow them down. And yet all developers feel the pressure to make messes in order to meet deadlines. In short, they don’t take the time to go fast!
  • 6. True professionals know that the second part of the conundrum is wrong. You will not make the deadline by making the mess. Indeed, the mess will slow you down instantly, and will force you to miss the deadline. The only way to make the deadline—the only way to go fast—is to keep the code as clean as possible at all times.
  • 7. How do I write Clean Code?
  • 8. What is Clean Code? “Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API. Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.” - Dave Thomas “Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.” - Grady Booch “I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.” - Bjarne Stroustrup You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem. - Ward Cunningham
  • 10. The Boy Scout Rule “Leave the campground cleaner than you found it” Code Rots and Degrades as time passes The Code has to be kept clean over time. We must take an active role in preventing the degradation.
  • 11. Naming ● Use intention revealing names ○ Why it exists ○ What it does ○ How it’s used ● Classes should have nouns or noun phrases ○ Don’t use Manager, Processor, Data or Info ● Methods should have verbs or verb phrases ● Accessor, Mutators or predicates should have get, set or is ● Use solution domain name ○ Factory, Visitor, Queue
  • 12. Functions ● Small ● Smaller than that!!! ● Does ONE THING ● Does ONLY ONE THING ● Blocks and Indentation ○ IF, While, For ● One level of abstraction per function ○ getHTML() ○ $parsed = Parser::render($url) ○ $xml->append($node)
  • 13. Functions ● Reads like a Top Down Narrative ○ To render the page we get all the content ○ To get all the content we extract it from the DB ○ To extract it from the DB we need to connect
  • 14. Function Arguments The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn’t be used anyway.
  • 15. Function Arguments - Flags Flag Arguments should be avoided. It does 1 thing if true and another thing when it’s false. render(true): renderForScreen() renderForTest()
  • 16. Function Argument - Objects It’s easier to pass Objects instead of a long argument list or array Rectangle makeRectangle(Double x1, Double y1, Double x2, Double y2) Rectangle makeRectangle(Point point1, Point point2)
  • 17. checkPassword(username, password) { user = $this->dataAccessor->findByUsername (username) valid= md5($user->getPassword()) === password if(valid) { Session.init(user) } else { Session.clear() } return valid } Have no side effect Sides effects are lies. BAD
  • 18. Enforce Temporal Coupling class ACL { function login(username, password) { this->user = this->findUser(username, password) this->getPermissions() this->startACLSession() } } BAD class ACL { function login(username, password) { this->user = this->findUser(username, password) this->permissions = this->getPermissions($this->user) this->startACLSession(this->permissions) } } BETTER
  • 19. if ($this->_sortBySet() === true) { ... } else if ($this->_sortByActor() === true) { ... } else if ($this->_sortByClip() === true) { ... } else { … } Make Conditions clear if (true === $bySetId && (true === empty($photoCollection) || true === empty($photoSet))) { ... } else if (true === $byActorId && (true === empty($photoCollection) || true === empty($actor))) { ... } else if (true === $byClipId && (true === empty($photoCollection) || true === empty($scene))) { ... } else { … } BAD BETTER
  • 20. sortingAlgorithmInterface = phosetSortingFactory->findSorter(sortBy) sorted list = sortingAlgorithmInterface ->sort(photosetList) Replace Conditions with Factory if ($this->_sortBySet() === true) { ... } else if ($this->_sortByActor() === true { ... } else if ($this->_sortByClip() === true) { ... } else { … } POLYMORPHISM GOODNESS
  • 22. Encapsulate Change Class UserRepository { function findById(id) { return Doctrine::getTable('Users')->createQuery(‘u’) ->where(‘u.id = ?’, id) ->fetchOne(); } } ORM MY GOD Class UserRepository { function findById(id) { userData = this->dataAccessor->findById(id) user = userFactory->create(userData) return user } } The only constant is Change.
  • 24. The Law of Demeter method f of a class C should only call the methods of these: ● C ● An object created by f ● An object passed as an argument to f ● An object held in an instance variable of C
  • 25. Class ACL { protected user function hasAccessToAdmin() { return this->user ->isAdmin() } } The Law of Demeter Class ACL { function hasAccessToAdmin() { return getUserManager() ->getUser(123) ->getProfile() ->isAdmin() } } BAD Class ACL { protected user protected aclVisitor function setVisitor(visitor) { … } function hasAccessToAdmin() { return this->aclVisitor ->isAdmin(this->user-getProfile()) } } Class AclVisitor { function isAdmin(profile) { return profile->isadmin() } } MEH PATTERNS!!!
  • 27. Don’t pass NULL, Don’t return NULL Throw an exception Return a NullObject findUser(ID) { user = this->dataAccessor->findById(ID) if(user == null) { user = new NullUser(); } return user } Class NullUser { function getName { return ‘’ //DO NOTHING } }
  • 31. Singleton Pattern "Singletons are the path of the dark side. Singletons lead to implicit dependencies. Implicit dependencies lead to global state. Global state leads to suffering."
  • 32. As events arrive from the outside world at a port, a technology-specific adapter converts it into a usable procedure call or message and passes it to the application. CreditCardService Hexagonal Architecture CreditCardService HTTP REST PHPUnit SOCKET ADAPTER
  • 33. When the application has something to send out, it sends it out through a port to an adapter, which creates the appropriate signals needed by the receiving technology (human or automated). CreditCardService Hexagonal Architecture CreditCardService HTML XML PHPUnit JSONP ADAPTER
  • 34. Class CreditCardService __construct(InputInterface, OutputInterface) { this->input = InputInterface this->output = OutputInterface } function process() { input = this->input->getInput() output = this->doProcessing(input) return this->ouput ->sendOutput(output) } } CreditCardService Hexagonal Architecture CreditCardService class CreditCardHTTPInputAdapter implements InputInterface{ function getInput() {..} } class CreditCardJSONPOutputAdapter implements OutputInterface{ function sendOutput(output) {..} }
  • 35. More stuff Command Query Separation Functions should either do something or answer something, but not both. DRY Don’t repeat yourself. Duplication may be the root of all evil in software. SOLID Single Responsibility, Open/Closed Principle, Liskov substitution principle, Interface segregation, Dependency Inversion Structured Programming Every function and every block has one Entry and one Exit Use Exceptions and Error Handling Functions should do one thing. Error handling is one thing. Thus, a function that handles errors should do nothing else.
  • 36. SHARE KNOWLEDGE KNOWLEDGE DECAYS FAST SLOW DOWN TO GO FAST NEVER ASK PERMISSION TO DO YOUR JOB CORRECTLY