SlideShare a Scribd company logo
1 of 27
Object Calisthenics
and
CLEAN CODE
in
PHP
About me
Hermenegildo Marin Júnior
PHP Developer
https://aboute.me/hermenegildo
@hmarinjr
A2C Agência
https://www.a2c.com.br/
Why?
● Maintainability
● Readability
● Testability
● Comprehensibility
From STUPID to SOLID Code!
STUPID
● Singleton
● Tight/strong Coupling
● Untestability
● Premature Optimization - YAGNI
● Indescriptive Naming
● Duplication
SOLID
● Single Responsibility Principle
● Open/Closed Principle
● Liskov Substitution Principle
● Interface Segregation Principle
● Dependency Inversion Principle
SINGLE RESPONSIBILITY PRINCIPLE
A class should have only one
reason to change.
Open-Close Principle
Software entities should be open
for extension, but closed for
modification.
Liskov substitution principle
Objects in a program should be
replaceable by instances of their
subtypes without changing
program accuracy
Interface Segregation Principle
Prefer more specific interfaces than a
generic
Dependency Inversion Principle
Depend on abstractions (interfaces)
rather than concrete classes
Object Calisthenics
Object Calisthenics are 9 language-
agnostic rules to help you write better
and cleaner code.
Jeff Bay
ThoughtWorks Anthology
Object Calisthenics
So, here’s an exercise that can help
you to internalize principles of good
object-oriented design and actually
use them in real life.
Jeff Bay
1. Only one level of indentation per method
class Board {
public String board() {
$buf = new StringBuilder();
// 0
for ($i = 0; $i < 10; $i++) {
// 1
for ($j = 0; $j < 10; $j++) {
// 2
$buf.append(data[i][j]);
}
$buf.append("n");
}
return $buf.toString();
}
}
class Board {
public String board() {
StringBuilder buf = new StringBuilder();
collectRows(buf);
return buf.toString();
}
private void collectRows(StringBuilder buf) {
for (int i = 0; i < 10; i++) {
collectRow(buf, i);
}
}
private void collectRow(StringBuilder buf, int row) {
for (int i = 0; i < 10; i++) {
buf.append(data[row][i]);
}
buf.append("n");
}
}
Extract method
https://refactoring.com/catalog/extractMethod.html
2. Don’t use ELSE keyword
function login($username, $password)
{
if ($this->isValid($username, $password)) {
$this->redirect("homepage");
} else {
$this->addFlash("error", "Bad credentials");
$this->redirect("login");
}
}
function login($username, $password) {
if ($this->isValid($username, $password)) {
return $this->redirect("homepage");
}
$this->addFlash("error", "Bad credentials");
return $this->redirect("login");
}
function login($username, $password) {
$redirectRoute = "homepage";
if (!$this->isValid($username, $password)) {
$this->addFlash("error", "Bad credentials");
$redirectRoute = "login";
}
$this->redirect($redirectRoute);
}
Early return
Variable
3. Wrap all primitives and strings
You simply have to encapsulate all the
primitives within objects.
If the variable of primitive type has a
behavior, it MUST be encapsulated.
http://wiki.c2.com/?PrimitiveObsession
4. First class collections
Any class that contains a collection
should contain no other member
variables.
5. One dot per line
You should not chain method calls.
Law of Demeter
Only talk to your immediate friends,
and don’t talk to strangers.
6. Don’t abbreviate
Why Do You Want To Abbreviate?
Write the same name over and over
again?
Method name too long?
https://williamdurand.fr/2012/01/24/designing-a-software-by-naming-things/
7. Keep all entities small
No class over 50 lines and no package
over 10 files.
8. No classes with more than two instance
variables
8. No classes with more than two instance
variables
Two kinds of classes, those that maintain
the state of a single instance variable,
and those that coordinate two separate
variables. Two is an arbitrary choice that
forces you to decouple your classes a lot.
9. No getters/setters/properties
class Game
{
private $score;
public function setScore($score)
{
$this->score = $score;
}
public function getScore()
{
return $this->score;
}
}
// Usage
$game = new Game();
$game->setScore(
$game->getScore() + ENEMY_DESTROYED_SCORE
);
// Game
public function addScore($delta)
{
$this->score += $delta;
}
// Usage
$game->addScore(ENEMY_DESTROYED_SCORE);
Tell, Don't Ask
Try them in your spare time, by
refactoring your Open Source projects for
instance. I think it is just a matter of
practice. Some rules are easy to follow,
and may help you.
Object calisthenics and best practices of development in php
Object calisthenics and best practices of development in php

More Related Content

Similar to Object calisthenics and best practices of development in php

DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)
Oleg Zinchenko
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
Nick Belhomme
 

Similar to Object calisthenics and best practices of development in php (20)

SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Čtvrtkon #53 - Štěpán Zikmund
Čtvrtkon #53 - Štěpán ZikmundČtvrtkon #53 - Štěpán Zikmund
Čtvrtkon #53 - Štěpán Zikmund
 
14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards14 Dependency Injection #burningkeyboards
14 Dependency Injection #burningkeyboards
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
PHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptxPHP OOP Lecture - 02.pptx
PHP OOP Lecture - 02.pptx
 
OOP
OOPOOP
OOP
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)
 
PHPID online Learning #6 Migration from procedural to OOP
PHPID online Learning #6 Migration from procedural to OOPPHPID online Learning #6 Migration from procedural to OOP
PHPID online Learning #6 Migration from procedural to OOP
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
Solid principles
Solid principlesSolid principles
Solid principles
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
SOLID
SOLIDSOLID
SOLID
 
Migration from Procedural to OOP
Migration from Procedural to OOP Migration from Procedural to OOP
Migration from Procedural to OOP
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Don't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionDon't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo Edition
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
 
Don't Be STUPID, Grasp SOLID - DrupalCon Prague
Don't Be STUPID, Grasp SOLID - DrupalCon PragueDon't Be STUPID, Grasp SOLID - DrupalCon Prague
Don't Be STUPID, Grasp SOLID - DrupalCon Prague
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
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
 
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, ...
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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...
 

Object calisthenics and best practices of development in php

  • 2. About me Hermenegildo Marin Júnior PHP Developer https://aboute.me/hermenegildo @hmarinjr A2C Agência https://www.a2c.com.br/
  • 3.
  • 4. Why? ● Maintainability ● Readability ● Testability ● Comprehensibility
  • 5. From STUPID to SOLID Code!
  • 6. STUPID ● Singleton ● Tight/strong Coupling ● Untestability ● Premature Optimization - YAGNI ● Indescriptive Naming ● Duplication
  • 7. SOLID ● Single Responsibility Principle ● Open/Closed Principle ● Liskov Substitution Principle ● Interface Segregation Principle ● Dependency Inversion Principle
  • 8. SINGLE RESPONSIBILITY PRINCIPLE A class should have only one reason to change.
  • 9. Open-Close Principle Software entities should be open for extension, but closed for modification.
  • 10. Liskov substitution principle Objects in a program should be replaceable by instances of their subtypes without changing program accuracy
  • 11. Interface Segregation Principle Prefer more specific interfaces than a generic
  • 12. Dependency Inversion Principle Depend on abstractions (interfaces) rather than concrete classes
  • 13. Object Calisthenics Object Calisthenics are 9 language- agnostic rules to help you write better and cleaner code. Jeff Bay ThoughtWorks Anthology
  • 14. Object Calisthenics So, here’s an exercise that can help you to internalize principles of good object-oriented design and actually use them in real life. Jeff Bay
  • 15. 1. Only one level of indentation per method class Board { public String board() { $buf = new StringBuilder(); // 0 for ($i = 0; $i < 10; $i++) { // 1 for ($j = 0; $j < 10; $j++) { // 2 $buf.append(data[i][j]); } $buf.append("n"); } return $buf.toString(); } } class Board { public String board() { StringBuilder buf = new StringBuilder(); collectRows(buf); return buf.toString(); } private void collectRows(StringBuilder buf) { for (int i = 0; i < 10; i++) { collectRow(buf, i); } } private void collectRow(StringBuilder buf, int row) { for (int i = 0; i < 10; i++) { buf.append(data[row][i]); } buf.append("n"); } } Extract method https://refactoring.com/catalog/extractMethod.html
  • 16. 2. Don’t use ELSE keyword function login($username, $password) { if ($this->isValid($username, $password)) { $this->redirect("homepage"); } else { $this->addFlash("error", "Bad credentials"); $this->redirect("login"); } } function login($username, $password) { if ($this->isValid($username, $password)) { return $this->redirect("homepage"); } $this->addFlash("error", "Bad credentials"); return $this->redirect("login"); } function login($username, $password) { $redirectRoute = "homepage"; if (!$this->isValid($username, $password)) { $this->addFlash("error", "Bad credentials"); $redirectRoute = "login"; } $this->redirect($redirectRoute); } Early return Variable
  • 17. 3. Wrap all primitives and strings You simply have to encapsulate all the primitives within objects. If the variable of primitive type has a behavior, it MUST be encapsulated. http://wiki.c2.com/?PrimitiveObsession
  • 18. 4. First class collections Any class that contains a collection should contain no other member variables.
  • 19. 5. One dot per line You should not chain method calls. Law of Demeter Only talk to your immediate friends, and don’t talk to strangers.
  • 20. 6. Don’t abbreviate Why Do You Want To Abbreviate? Write the same name over and over again? Method name too long? https://williamdurand.fr/2012/01/24/designing-a-software-by-naming-things/
  • 21. 7. Keep all entities small No class over 50 lines and no package over 10 files.
  • 22. 8. No classes with more than two instance variables
  • 23. 8. No classes with more than two instance variables Two kinds of classes, those that maintain the state of a single instance variable, and those that coordinate two separate variables. Two is an arbitrary choice that forces you to decouple your classes a lot.
  • 24. 9. No getters/setters/properties class Game { private $score; public function setScore($score) { $this->score = $score; } public function getScore() { return $this->score; } } // Usage $game = new Game(); $game->setScore( $game->getScore() + ENEMY_DESTROYED_SCORE ); // Game public function addScore($delta) { $this->score += $delta; } // Usage $game->addScore(ENEMY_DESTROYED_SCORE); Tell, Don't Ask
  • 25. Try them in your spare time, by refactoring your Open Source projects for instance. I think it is just a matter of practice. Some rules are easy to follow, and may help you.