SlideShare uma empresa Scribd logo
1 de 56
Baixar para ler offline
Object Calisthenics
9 steps to better software design today, by Jeff Bay
By: Darwin
April 30, 2014
Before we start...
As developers we all are aware of the core concepts that make up good OO code…
cohesion, loose coupling, no redundancy, encapsulation,
testability, readability, maintainability, etc.
But the question is, are we really implementing these concepts properly in code?
Why does my
CODE suck?
Is it MAINTAINABLE? Is it READABLE?
Is it TESTABLE?Is it REUSABLE?
Let’s ask ourselves of the following...
And what does it have to do with good OO coding?
What is Object Calisthenics?
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Calisthenics ( cal·is·then·ics )
Definition :
Calisthenics are a form of dynamic exercise consisting of a variety of
simple, often rhythmical, movements, generally using minimal equipment or
apparatus.
Object Calisthenics
Definition :
A variety of simple, often rhythmical, exercises to achieve better OO
(Object Oriented) design and code quality.
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
1. One level of indentation per method
2. Don’t use the ELSE keyword
3. Wrap all primitives and Strings
4. First class collections
5. One -> per line
6. Don’t abbreviate
7. Keep all entities small
8. Limit the number of instance variables
in a class (max: 2~5)
9. Do use accessors (getters/setters)
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #1
“Only one level of indentation per
method”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
function validateProducts ($products) {
foreach ($products as $rawProduct) {
$fields = array_keys($rawProduct);
foreach ($requiredFields as $requiredField) {
if (!in_array($requiredField, $fields)) {
$valid = false;
}
}
}
}
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #1: Only one level of indentation per method
• A giant method lacks cohesiveness.
• Try to ensure that each method does exactly one thing – one
control structure, or one block of statements, per method.
• Nested control structures in a method, works at multiple levels of
abstraction which means it does more than one thing.
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Basically…
• Do one thing per method
• one control structure
• one block of statements
• Avoid nested control structures
• it means you are doing more than one thing
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
function validateProductList ( $products) {
$invalidProducts = array_filter($products, ‘isInvalidProduct’ );
return (count($invalidProducts ) === 0);
}
function isInvalidProduct ( $rawProduct) {
$requiredFields = array(‘price’, ‘name’, ‘description’, ‘type’);
$fields = array_keys($rawProduct);
$missingFields = array_diff($requiredFields , $fields);
return (count($missingFields ) > 0);
}
reusable method
Benefits…
• Cohesiveness
• Methods do only one thing
• Increases re-use
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #2
“Do not use the ‘else‘ keyword”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
if ($form->isValid) {
$repository = $this->getRepository( ‘MyBundle:Post’ );
if (!$repository->exists($entity)) {
$repository->save($entity);
return $this->redirect(‘create_ok’);
} else {
$error = “Post Title already exists” ;
return array(‘form’ => $form, ‘error’ => $error);
}
} else {
$error = “Invalid fields” ;
return array(‘form’ => $form, ‘error’ => $error);
}
ELSE
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #2: Do not use the ‘else’ keyword
• Conditionals are also a frequent source of duplication.
if (status == ‘DONE’) {
doSomething();
} else {
…
}
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Basically…
• Nested conditionals & long case statements
• hard to follow
• Frequent source of code duplication
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
$repository = $this->getRepository( ‘MyBundle:Post’ );
if (!$form->isValid) {
return array(‘form’ => $form, ‘error’ => ‘Invalid fields’ );
}
if ($repository->exists($entity)) {
return array(‘form’ => $form, ‘error’ => ‘Post Title already exists’ );
}
$repository->save($entity);
return $this->redirect(‘create_ok’);
early return
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• Helps avoid code duplication
• Makes code clearer, easier to read
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #3
“Wrap all primitive types and strings, if
it has behavior”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
class UIComponent
{
//...
public function repaint($animate = true) {
//...
}
}
//...
$component->repaint(false);
unclear operation
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #3: Wrap all primitive types and strings, if it has behavior
• To give the programmer additional information about what the
value is and why it is being used
• This rule tries to encapsulate all the primitives within objects for
these to work in all our code in an OO-way.
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
class UIComponent
{
//...
public function repaint(Animate $animate) {
//...
}
}
class Animate
{
public $animate
public function __construct( $animate = true) {
$this->animate = $animate;
}
}
//...
$component->repaint(new Animate(false));
This can now
encapsulate all
animation related
operations
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
<?php
class IntegerNumber
{
private $number;
public function __construct($number)
{
$this->number = $number;
}
//...
}
An example of how we
can wrap the int
primitive.
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
<?php
class Item
{
final public static function find(Id $id)
{
// do find...
}
final public static function create(Id $id, array $data)
{
// do create...
}
}
$id is now
guaranteed
to be valid.
$id is now
guaranteed
to be valid.
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• More maintainable code
• Helps identify what should be an Object
• Type hinting
• Encapsulation of operations
• Context of value is more obvious
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #4
“Use first class collections”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
$collection->getIterator();
$collection->filter(...);
$collection->append(...);
$collection->map(...);
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #4: Use first class collections
• Any class that contains a collection should contain no other
member variables.
• Each collection gets wrapped in its own class. So now, behaviors
related to the collection have a home.
• Class will contain related behaviors.
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
class Items
{
private $item = [];
public function add(Item $item, array $data)
{
// do add...
}
public function filter(array $filters)
{
// do filter...
}
}
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• Implements collection operations
• Uses SPL interfaces
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #5
“Only one -> per line”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
$this->base_url = $this->CI->config->site_url().’/’.$this->CI->uri->segment(1).$this->CI->uri-
>slash_segment(2, ‘both’);
$this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, ‘leading’);
$this->base_uri = $this->getCI()->getUriBuilder()->getBaseUri(‘leading’);
Move everything to uri object
no whitespace
properties are harder to mock
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
$this->manager->getConfig()->getSegment()->setName(‘foo’);
properties are harder to mock
previous call could return NULL
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #5: Only one -> per line
• An object should not deal with two other objects at once
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Basically…
• Multiple ->
• indicate misplaced responsibilities
• violate encapsulation
• Law of Demeter
• “Talk only to your friends”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• Readability
• Easier Mocking
• Easier to Debug
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #6
“Do NOT abbreviate”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
if ($sx >= $sy) {
if ($sx > $strSysMatImgW ) {
//…
}
if ($ny > $strSysMatImgH ) {
//…
}
} else {
if ($sy > $strSysMatImgH ) {
//…
}
if ($nx > $strSysMatImgW ) {
//…
}
}
?
?
?
?
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #6: Do NOT abbreviate
• Abbreviations can be confusing, and they tend to hide larger
problems.
• Keep class and method names to 1-2 words, and avoid names that
duplicate the context.
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Basically…
• Keep names to one-two words
• class names
• method names
• entities
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
function getPage($data) { ... }
function startProcess() { ... }
$tr->process(“site.login”);
Use a thesaurus: fork,
create, begin, open
Easy understanding,
complete scope:
$translatorService
Use clearer names:
fetchPage()
downloadPage()
get from where?
table row?
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• Clearer communication
• Indicates underlying problems
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #7
“Keep all entities small”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #7: Keep classes small
• 200 lines per class (including docblocks)
• 15 - 20 lines per method
• 10 methods per class
• 15 classes per namespace (package or folder)
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• Easier to grasp quickly
• Single responsibility
• Objective method
• Slimmer namespaces
• Less clunky folders
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #8
“Limit the number of instance variables
in a class (max: 2 5)”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
class Client
{
private $_adapter;
private $_cache;
private $_logger;
//...
}
Limit: 2 - 5
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• Shorter dependency list
• Better understanding of commonality
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
OC #9
“Do not use accessors (getter/setter)”
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
class Tally
{
public $total = 0;
public function add($amount)
{
$this->total += $amount;
}
}
$tally = new Tally();
$tally->add(1);
// some other code...
$tally->total = -1;
// some other code...
$tally->add(1);
echo $tally->total . PHP_EOL
$total can be changed without
this instance knowing
causes unexpected results
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
class Tally
{
private $total = 0;
public function add($amount)
{
$this->total += $amount;
}
public function getTotal()
{
return $this->total;
}
}
$tally = new Tally();
$tally->add(1);
$tally->add(1);
echo $tally->getTotal() . PHP_EOL
total cannot be “reset”
no unexpected results
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
Benefits…
• Injector operations
• Encapsulation of transformations
Object Calisthenics: 9 steps to better software design today, by Jeff Bay
1. “Only one level of indentation per method”
2. “Do not use the ‘else‘ keyword”
3. “Wrap all primitive types and strings, if it has behavior”
4. “Use first class collections”
5. “Only one -> per line”
6. “Do NOT abbreviate”
7. “Keep all entities small”
8. “Limit the number of instance variables in a class (max: 2 5)”
9. “Do not use accessors (getter/setter)”
The Recap...
• To visualize and implement the holy grail of object oriented
programming – encapsulation of data
• To use polymorphism appropriately
• To encourage concise and straightforward naming standards
• To craft code that has no duplication in code or idea
The Aim...
• http://www.bennadel.com/resources/uploads/2012/ObjectCalisthenics.pdf
• http://www.slideshare.net/rdohms/your-code-sucks-lets-fix-it
• http://www.slideshare.net/chadwick0678/getting-your-code-into-shape-with-object
References
Object Calisthenics

Mais conteúdo relacionado

Destaque

kriza Sports PR Services
kriza Sports PR Services kriza Sports PR Services
kriza Sports PR Services dandoni
 
Physical Education are based on the natural Physical education of the primit...
Physical Education  are based on the natural Physical education of the primit...Physical Education  are based on the natural Physical education of the primit...
Physical Education are based on the natural Physical education of the primit...Rose Manlapaz
 
Rhythmic Gymnastics School Activity
Rhythmic Gymnastics School ActivityRhythmic Gymnastics School Activity
Rhythmic Gymnastics School ActivityAnkita Dandekar
 
Object calisthenics (PyCon Poland 2016)
Object calisthenics (PyCon Poland 2016)Object calisthenics (PyCon Poland 2016)
Object calisthenics (PyCon Poland 2016)Paweł Lewtak
 
PEShare.co.uk Shared Resource
PEShare.co.uk Shared ResourcePEShare.co.uk Shared Resource
PEShare.co.uk Shared Resourcepeshare.co.uk
 
Age sex Pyramids Presentation
Age sex Pyramids PresentationAge sex Pyramids Presentation
Age sex Pyramids PresentationTafadzwa Bere
 
SGP - Sport Psychology
SGP - Sport PsychologySGP - Sport Psychology
SGP - Sport Psychology118620
 
Reading age sex pyramid - lesson 5
Reading age sex pyramid - lesson 5Reading age sex pyramid - lesson 5
Reading age sex pyramid - lesson 5Ms Geoflake
 
17 Traits Of A Teacher
17 Traits Of A Teacher17 Traits Of A Teacher
17 Traits Of A TeacherKidzrio
 
2012 NCSP.Cultural Influences of Dance in Physical Education
2012 NCSP.Cultural Influences of Dance in Physical Education2012 NCSP.Cultural Influences of Dance in Physical Education
2012 NCSP.Cultural Influences of Dance in Physical EducationUp Danzprof
 
Qualification of Teacher As per NCTE
Qualification of Teacher As per NCTEQualification of Teacher As per NCTE
Qualification of Teacher As per NCTEsj202
 
Organisation of Intramurals and Drawing fixtures
Organisation of Intramurals and Drawing fixturesOrganisation of Intramurals and Drawing fixtures
Organisation of Intramurals and Drawing fixturesNEERAJ KUMAR MEHRA
 
Pdhpe Sports Psychology
Pdhpe Sports PsychologyPdhpe Sports Psychology
Pdhpe Sports Psychologypdhpemag
 
TEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXT
TEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXTTEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXT
TEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXTMustheena k
 

Destaque (17)

Sports Psychology in Action
Sports Psychology in ActionSports Psychology in Action
Sports Psychology in Action
 
kriza Sports PR Services
kriza Sports PR Services kriza Sports PR Services
kriza Sports PR Services
 
Strategy of Sport for all
Strategy of Sport for all Strategy of Sport for all
Strategy of Sport for all
 
Physical Education are based on the natural Physical education of the primit...
Physical Education  are based on the natural Physical education of the primit...Physical Education  are based on the natural Physical education of the primit...
Physical Education are based on the natural Physical education of the primit...
 
Rhythmic Gymnastics School Activity
Rhythmic Gymnastics School ActivityRhythmic Gymnastics School Activity
Rhythmic Gymnastics School Activity
 
Object calisthenics (PyCon Poland 2016)
Object calisthenics (PyCon Poland 2016)Object calisthenics (PyCon Poland 2016)
Object calisthenics (PyCon Poland 2016)
 
PEShare.co.uk Shared Resource
PEShare.co.uk Shared ResourcePEShare.co.uk Shared Resource
PEShare.co.uk Shared Resource
 
Age sex Pyramids Presentation
Age sex Pyramids PresentationAge sex Pyramids Presentation
Age sex Pyramids Presentation
 
SGP - Sport Psychology
SGP - Sport PsychologySGP - Sport Psychology
SGP - Sport Psychology
 
Reading age sex pyramid - lesson 5
Reading age sex pyramid - lesson 5Reading age sex pyramid - lesson 5
Reading age sex pyramid - lesson 5
 
17 Traits Of A Teacher
17 Traits Of A Teacher17 Traits Of A Teacher
17 Traits Of A Teacher
 
Why Sports Psychology?
Why Sports Psychology?Why Sports Psychology?
Why Sports Psychology?
 
2012 NCSP.Cultural Influences of Dance in Physical Education
2012 NCSP.Cultural Influences of Dance in Physical Education2012 NCSP.Cultural Influences of Dance in Physical Education
2012 NCSP.Cultural Influences of Dance in Physical Education
 
Qualification of Teacher As per NCTE
Qualification of Teacher As per NCTEQualification of Teacher As per NCTE
Qualification of Teacher As per NCTE
 
Organisation of Intramurals and Drawing fixtures
Organisation of Intramurals and Drawing fixturesOrganisation of Intramurals and Drawing fixtures
Organisation of Intramurals and Drawing fixtures
 
Pdhpe Sports Psychology
Pdhpe Sports PsychologyPdhpe Sports Psychology
Pdhpe Sports Psychology
 
TEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXT
TEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXTTEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXT
TEACHING AND LEARNING RESOURCES: FORMAL AND INFORMAL CONTEXT
 

Semelhante a Object Calisthenics

Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toAlexander Makarov
 
DeKnowledge - Try us
DeKnowledge - Try usDeKnowledge - Try us
DeKnowledge - Try usBob Pinto
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?devObjective
 
The Professional Programmer
The Professional ProgrammerThe Professional Programmer
The Professional ProgrammerDave Cross
 
Object calisthenics (PHPCon Poland 2016)
Object calisthenics (PHPCon Poland 2016)Object calisthenics (PHPCon Poland 2016)
Object calisthenics (PHPCon Poland 2016)Paweł Lewtak
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?ColdFusionConference
 
Building Your App SDK with Swift
Building Your App SDK with SwiftBuilding Your App SDK with Swift
Building Your App SDK with SwiftJordan Yaker
 
Unlocking the Power of Iteration
Unlocking the Power of IterationUnlocking the Power of Iteration
Unlocking the Power of IterationClement Ho
 
Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesiMasters
 
What Is DevOps, Really
What Is DevOps, ReallyWhat Is DevOps, Really
What Is DevOps, ReallyXebiaLabs
 
Introduction to Meteor - revised edition
Introduction to Meteor - revised editionIntroduction to Meteor - revised edition
Introduction to Meteor - revised editionStephan Hochhaus
 
Practicing Red, Green, Refactor!
Practicing Red, Green, Refactor!Practicing Red, Green, Refactor!
Practicing Red, Green, Refactor!XPDays
 
Behaviour driven infrastructure
Behaviour driven infrastructureBehaviour driven infrastructure
Behaviour driven infrastructureLindsay Holmwood
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#Daniel Fisher
 
Don't let your tests slow you down
Don't let your tests slow you downDon't let your tests slow you down
Don't let your tests slow you downDaniel Irvine
 

Semelhante a Object Calisthenics (20)

2009-02 Oops!
2009-02 Oops!2009-02 Oops!
2009-02 Oops!
 
I os tdd-with-bdd
I os tdd-with-bddI os tdd-with-bdd
I os tdd-with-bdd
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading to
 
DeKnowledge - Try us
DeKnowledge - Try usDeKnowledge - Try us
DeKnowledge - Try us
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
The Professional Programmer
The Professional ProgrammerThe Professional Programmer
The Professional Programmer
 
Object calisthenics (PHPCon Poland 2016)
Object calisthenics (PHPCon Poland 2016)Object calisthenics (PHPCon Poland 2016)
Object calisthenics (PHPCon Poland 2016)
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
Building Your App SDK with Swift
Building Your App SDK with SwiftBuilding Your App SDK with Swift
Building Your App SDK with Swift
 
Unlocking the Power of Iteration
Unlocking the Power of IterationUnlocking the Power of Iteration
Unlocking the Power of Iteration
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul Jones
 
What Is DevOps, Really
What Is DevOps, ReallyWhat Is DevOps, Really
What Is DevOps, Really
 
Introduction to Meteor - revised edition
Introduction to Meteor - revised editionIntroduction to Meteor - revised edition
Introduction to Meteor - revised edition
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Practicing Red, Green, Refactor!
Practicing Red, Green, Refactor!Practicing Red, Green, Refactor!
Practicing Red, Green, Refactor!
 
Behaviour driven infrastructure
Behaviour driven infrastructureBehaviour driven infrastructure
Behaviour driven infrastructure
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
Don't let your tests slow you down
Don't let your tests slow you downDon't let your tests slow you down
Don't let your tests slow you down
 

Mais de KLabCyscorpions-TechBlog (12)

Auto Layout on Xcode 5
Auto Layout on Xcode 5Auto Layout on Xcode 5
Auto Layout on Xcode 5
 
Code Review for iOS
Code Review for iOSCode Review for iOS
Code Review for iOS
 
Why You're A Bad PHP Programmer
Why You're A Bad PHP ProgrammerWhy You're A Bad PHP Programmer
Why You're A Bad PHP Programmer
 
Redis Set Go
Redis Set GoRedis Set Go
Redis Set Go
 
Redis Beyond
Redis BeyondRedis Beyond
Redis Beyond
 
X-Debug in Php Storm
X-Debug in Php StormX-Debug in Php Storm
X-Debug in Php Storm
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Php + MySql Optimization
Php + MySql OptimizationPhp + MySql Optimization
Php + MySql Optimization
 
Mysql Optimization
Mysql OptimizationMysql Optimization
Mysql Optimization
 
MVC Web Application
MVC Web ApplicationMVC Web Application
MVC Web Application
 
AfNetworking vs. Native + Caching
AfNetworking vs. Native + CachingAfNetworking vs. Native + Caching
AfNetworking vs. Native + Caching
 
Bash
BashBash
Bash
 

Último

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 

Último (20)

Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

Object Calisthenics

  • 1. Object Calisthenics 9 steps to better software design today, by Jeff Bay By: Darwin April 30, 2014
  • 2. Before we start... As developers we all are aware of the core concepts that make up good OO code… cohesion, loose coupling, no redundancy, encapsulation, testability, readability, maintainability, etc. But the question is, are we really implementing these concepts properly in code?
  • 3. Why does my CODE suck? Is it MAINTAINABLE? Is it READABLE? Is it TESTABLE?Is it REUSABLE? Let’s ask ourselves of the following...
  • 4. And what does it have to do with good OO coding? What is Object Calisthenics? Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 5. Calisthenics ( cal·is·then·ics ) Definition : Calisthenics are a form of dynamic exercise consisting of a variety of simple, often rhythmical, movements, generally using minimal equipment or apparatus. Object Calisthenics Definition : A variety of simple, often rhythmical, exercises to achieve better OO (Object Oriented) design and code quality. Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 6. 1. One level of indentation per method 2. Don’t use the ELSE keyword 3. Wrap all primitives and Strings 4. First class collections 5. One -> per line 6. Don’t abbreviate 7. Keep all entities small 8. Limit the number of instance variables in a class (max: 2~5) 9. Do use accessors (getters/setters) Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 7. OC #1 “Only one level of indentation per method” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 8. function validateProducts ($products) { foreach ($products as $rawProduct) { $fields = array_keys($rawProduct); foreach ($requiredFields as $requiredField) { if (!in_array($requiredField, $fields)) { $valid = false; } } } } Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 9. OC #1: Only one level of indentation per method • A giant method lacks cohesiveness. • Try to ensure that each method does exactly one thing – one control structure, or one block of statements, per method. • Nested control structures in a method, works at multiple levels of abstraction which means it does more than one thing. Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 10. Basically… • Do one thing per method • one control structure • one block of statements • Avoid nested control structures • it means you are doing more than one thing Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 11. Object Calisthenics: 9 steps to better software design today, by Jeff Bay function validateProductList ( $products) { $invalidProducts = array_filter($products, ‘isInvalidProduct’ ); return (count($invalidProducts ) === 0); } function isInvalidProduct ( $rawProduct) { $requiredFields = array(‘price’, ‘name’, ‘description’, ‘type’); $fields = array_keys($rawProduct); $missingFields = array_diff($requiredFields , $fields); return (count($missingFields ) > 0); } reusable method
  • 12. Benefits… • Cohesiveness • Methods do only one thing • Increases re-use Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 13. OC #2 “Do not use the ‘else‘ keyword” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 14. if ($form->isValid) { $repository = $this->getRepository( ‘MyBundle:Post’ ); if (!$repository->exists($entity)) { $repository->save($entity); return $this->redirect(‘create_ok’); } else { $error = “Post Title already exists” ; return array(‘form’ => $form, ‘error’ => $error); } } else { $error = “Invalid fields” ; return array(‘form’ => $form, ‘error’ => $error); } ELSE Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 15. OC #2: Do not use the ‘else’ keyword • Conditionals are also a frequent source of duplication. if (status == ‘DONE’) { doSomething(); } else { … } Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 16. Basically… • Nested conditionals & long case statements • hard to follow • Frequent source of code duplication Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 17. $repository = $this->getRepository( ‘MyBundle:Post’ ); if (!$form->isValid) { return array(‘form’ => $form, ‘error’ => ‘Invalid fields’ ); } if ($repository->exists($entity)) { return array(‘form’ => $form, ‘error’ => ‘Post Title already exists’ ); } $repository->save($entity); return $this->redirect(‘create_ok’); early return Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 18. Benefits… • Helps avoid code duplication • Makes code clearer, easier to read Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 19. OC #3 “Wrap all primitive types and strings, if it has behavior” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 20. class UIComponent { //... public function repaint($animate = true) { //... } } //... $component->repaint(false); unclear operation Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 21. OC #3: Wrap all primitive types and strings, if it has behavior • To give the programmer additional information about what the value is and why it is being used • This rule tries to encapsulate all the primitives within objects for these to work in all our code in an OO-way. Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 22. class UIComponent { //... public function repaint(Animate $animate) { //... } } class Animate { public $animate public function __construct( $animate = true) { $this->animate = $animate; } } //... $component->repaint(new Animate(false)); This can now encapsulate all animation related operations Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 23. <?php class IntegerNumber { private $number; public function __construct($number) { $this->number = $number; } //... } An example of how we can wrap the int primitive. Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 24. <?php class Item { final public static function find(Id $id) { // do find... } final public static function create(Id $id, array $data) { // do create... } } $id is now guaranteed to be valid. $id is now guaranteed to be valid. Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 25. Benefits… • More maintainable code • Helps identify what should be an Object • Type hinting • Encapsulation of operations • Context of value is more obvious Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 26. OC #4 “Use first class collections” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 28. OC #4: Use first class collections • Any class that contains a collection should contain no other member variables. • Each collection gets wrapped in its own class. So now, behaviors related to the collection have a home. • Class will contain related behaviors. Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 29. class Items { private $item = []; public function add(Item $item, array $data) { // do add... } public function filter(array $filters) { // do filter... } } Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 30. Benefits… • Implements collection operations • Uses SPL interfaces Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 31. OC #5 “Only one -> per line” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 32. $this->base_url = $this->CI->config->site_url().’/’.$this->CI->uri->segment(1).$this->CI->uri- >slash_segment(2, ‘both’); $this->base_uri = $this->CI->uri->segment(1).$this->CI->uri->slash_segment(2, ‘leading’); $this->base_uri = $this->getCI()->getUriBuilder()->getBaseUri(‘leading’); Move everything to uri object no whitespace properties are harder to mock Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 33. $this->manager->getConfig()->getSegment()->setName(‘foo’); properties are harder to mock previous call could return NULL Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 34. OC #5: Only one -> per line • An object should not deal with two other objects at once Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 35. Basically… • Multiple -> • indicate misplaced responsibilities • violate encapsulation • Law of Demeter • “Talk only to your friends” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 36. Benefits… • Readability • Easier Mocking • Easier to Debug Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 37. OC #6 “Do NOT abbreviate” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 38. if ($sx >= $sy) { if ($sx > $strSysMatImgW ) { //… } if ($ny > $strSysMatImgH ) { //… } } else { if ($sy > $strSysMatImgH ) { //… } if ($nx > $strSysMatImgW ) { //… } } ? ? ? ? Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 39. OC #6: Do NOT abbreviate • Abbreviations can be confusing, and they tend to hide larger problems. • Keep class and method names to 1-2 words, and avoid names that duplicate the context. Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 40. Basically… • Keep names to one-two words • class names • method names • entities Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 41. function getPage($data) { ... } function startProcess() { ... } $tr->process(“site.login”); Use a thesaurus: fork, create, begin, open Easy understanding, complete scope: $translatorService Use clearer names: fetchPage() downloadPage() get from where? table row? Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 42. Benefits… • Clearer communication • Indicates underlying problems Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 43. OC #7 “Keep all entities small” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 44. OC #7: Keep classes small • 200 lines per class (including docblocks) • 15 - 20 lines per method • 10 methods per class • 15 classes per namespace (package or folder) Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 45. Benefits… • Easier to grasp quickly • Single responsibility • Objective method • Slimmer namespaces • Less clunky folders Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 46. OC #8 “Limit the number of instance variables in a class (max: 2 5)” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 47. class Client { private $_adapter; private $_cache; private $_logger; //... } Limit: 2 - 5 Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 48. Benefits… • Shorter dependency list • Better understanding of commonality Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 49. OC #9 “Do not use accessors (getter/setter)” Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 50. class Tally { public $total = 0; public function add($amount) { $this->total += $amount; } } $tally = new Tally(); $tally->add(1); // some other code... $tally->total = -1; // some other code... $tally->add(1); echo $tally->total . PHP_EOL $total can be changed without this instance knowing causes unexpected results Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 51. class Tally { private $total = 0; public function add($amount) { $this->total += $amount; } public function getTotal() { return $this->total; } } $tally = new Tally(); $tally->add(1); $tally->add(1); echo $tally->getTotal() . PHP_EOL total cannot be “reset” no unexpected results Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 52. Benefits… • Injector operations • Encapsulation of transformations Object Calisthenics: 9 steps to better software design today, by Jeff Bay
  • 53. 1. “Only one level of indentation per method” 2. “Do not use the ‘else‘ keyword” 3. “Wrap all primitive types and strings, if it has behavior” 4. “Use first class collections” 5. “Only one -> per line” 6. “Do NOT abbreviate” 7. “Keep all entities small” 8. “Limit the number of instance variables in a class (max: 2 5)” 9. “Do not use accessors (getter/setter)” The Recap...
  • 54. • To visualize and implement the holy grail of object oriented programming – encapsulation of data • To use polymorphism appropriately • To encourage concise and straightforward naming standards • To craft code that has no duplication in code or idea The Aim...