SlideShare a Scribd company logo
Writing better
code with
Object Calisthenics
Lucas Arruda
lucas@ciandt.com
github.com/larruda
Adapted from Jeff Bay’s paper from
“The ThoughtWorks Anthology”
and Guilherme Blanco’s presentation.
Calis...what?!
7 code qualities
cohesion
loose coupling
no redundancy
encapsulation
testability
readability
focus
9
rules of thumb
1. One level of indentation per method
class Board {
...
String board() {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++)
buf.append(data[i][j]);
buf.append(“n”);
}
return buf.toString();
}
}
1. One level of indentation per method
class Board {
...
String Board() {
StringBuffer buf = new StringBuffer();
collectRows(buf);
return buf.toString();
}
void collectRows(StringBuffer buf) {
for (int i = 0; i < 10; i++)
collectRow(buf, i);
}
void collectRow(StringBuffer buf, int row) {
for (int i = 0; i < 10; i++)
Buf.append(data[row][i]);
buf.append(“n”);
}
}
1. One level of indentation per method
public function validateForm($filters='', $validators='', $options='')
{
$data = $_POST;
$input = new Zend_Filter_Input($filters, $validators, $data);
$input->setDefaultEscapeFilter(new Zend_Filter_StringTrim());
if ($input->hasInvalid() || $input->hasMissing()) {
foreach ($input->getMessages() as $field => $messageList) {
foreach ($messageList as $message) {
if (strpos($message, "empty")) {
throw new Tss_FormException(
"The field {$field} cannot be empty!",
3, 'javascript:history.back();'
);
} else {
throw new Tss_FormException(
"{$message}", 3, 'javascript:history.back();'
);
}
}
}
}
return $input;
}
1. One level of indentation per method
public function validateForm($filters='', $validators='', $options='')
{
$data = $_POST;
$input = new Zend_Filter_Input($filters, $validators, $data);
$input->setDefaultEscapeFilter(new Zend_Filter_StringTrim());
if ( ! ($input->hasInvalid() || $input->hasMissing())) {
return $input;
}
foreach ($input->getMessages() as $field => $messageList) {
foreach ($messageList as $message) {
if (strpos($message, "empty")) {
throw new Tss_FormException(
"The field {$field} cannot be empty!",
3, 'javascript:history.back();'
);
} else {
throw new Tss_FormException(
"{$message}", 3, 'javascript:history.back();'
);
}
}
}
}
1. One level of indentation per method
public function validateForm($filters='', $validators='', ...
{
$data = $_POST;
$input = new Zend_Filter_Input ($filters, $validators, $data);
$input->setDefaultEscapeFilter( new Zend_Filter_StringTrim ());
if ( ! ($input->hasInvalid() || $input->hasMissing())) {
return $input;
}
foreach ($input->getMessages() as $field => $messageList) {
foreach ($messageList as $message) {
$errorMessage = (strpos($message, "empty") === false)
? "The field {$field} cannot be empty!"
: "{$message}";
throw new Tss_FormException (
$errorMessage, 3, 'javascript:history.back();'
);
}
}
}
1. One level of indentation per method
public function validateForm($filters='', $validators='', ...
{
$data = $_POST;
$input = new Zend_Filter_Input ($filters, $validators, $data);
$input->setDefaultEscapeFilter( new Zend_Filter_StringTrim ());
if ( ! ($input->hasInvalid() || $input->hasMissing())) {
return $input;
}
foreach ($input->getMessages() as $field => $messageList) {
$messageKey = key($message);
$message = $message[$messageKey];
$errorMessage = (strpos($message, "empty") === false)
? "The field {$field} cannot be empty!"
: "{$message}";
throw new Tss_FormException (
$errorMessage, 3, 'javascript:history.back();'
);
}
}
2. Don’t use the ELSE keyword
if (status == DONE) {
doSomething();
} else {
…
}
YOU
MUST BE
JOKING!!!
2. Don’t use the ELSE keyword
class Board {
...
String board(StringBuffer buf) {
if (buf.length()) {
return buf.toString();
}
else {
collectRows(buf);
return buf.toString();
}
}
...
}
2. Don’t use the ELSE keyword
class Board {
...
String board(StringBuffer buf) {
if (!buf.length()) {
collectRows(buf);
}
return buf.toString();
}
...
}
2. Don’t use the ELSE keyword
function login() {
$login = $this->input->post('email', true);
$password = $this->input->post('password', true);
$reference = $this->input->post('reference', true);
if ($this->clients_model->login($login, $password)) {
redirect( $reference);
} else {
$this->session->set_flashdata(
'error' , 'User or password invalid.'
);
$this->session->set_flashdata( 'reference', $reference);
redirect( 'clients');
}
}
2. Don’t use the ELSE keyword
function login() {
$login = $this->input->post('email', true);
$password = $this->input->post('password', true);
$reference = $this->input->post('reference', true);
if (!$this->clients_model->login($login, $password)) {
$this->session->set_flashdata(
'error' , 'User or password invalid.'
);
$this->session->set_flashdata( 'reference', $reference);
$reference = 'clients';
}
redirect($reference);
}
3. Wrap all primitives and Strings
If the primitive type has a behavior it
should be encapsulated
3. Wrap all primitives and Strings
class UIComponent
{
// ...
public function repaint($animate = true)
{
// …
}
// ...
$component->repaint(false);
}
3. Wrap all primitives and Strings
class UIComponent
{
// ...
public function repaint(Animate $animate)
{
// ...
}
}
class Animate
{
public $animate;
public function __construct($animate = true)
{
$this->animate = $animate;
}
}
// ...
$component->repaint(new Animate(false));
4. First class collections
Any class that contains a collection/array
should not contain any other member
variables
Java Collections follow this rule
4. First class collections
Transversable
Countable
Iterator
Filtering
Mapping
Combining
5. One dot/arrow per line
Sign of misplaced responsibilities
The Law of Demeter
“Only talk to your friends”
5. One dot/arrow per line
class Board {
...
class Piece {
...
String representation;
}
class Location {
...
Piece current;
}
String boardRepresentation () {
StringBuffer buf = new StringBuffer();
for (Location l: squares())
buf .append(l.current.representation .substring(0,
1));
return buf.toString();
}
}
5. One dot/arrow per line
class Board {
...
class Piece {
...
private String representation;
String character() {
return representation.substring(0, 1);
}
void addTo(StringBuffer buf) {
buf.append(character());
}
}
class Location {
...
private Piece current;
void addTo(StringBuffer buf) {
current.addTo(buf);
}
}
String boardRepresentation() {
StringBuffer buf = new StringBuffer();
for (Location l: squares())
l.addTo(buf);
return buf.toString();
}
}
6. Don’t abbreviate
Are you writing the same name repeatedly?
method being used multiple times
sign of code duplication
Is the method name too long?
class with multiple responsibilities
missing additional class
redundancy
7. Keep all entities small
Java
No class over 50 lines
No packages over 10 files
PHP
No class over 100 lines
No packages over 15 files
Packages, like classes, should be
cohesive and have a purpose
8. No classes with more than two/five instance variables
Improve cohesion
Split on more entities
9. No getters/setters/properties
Improve encapsulation
“Tell, don’t ask”
Q&A
ciandt.com
http://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf
http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php
https://www.youtube.com/watch?v=ftBUHrxfOcc
THANKS
FOR
BEING
HERE!
ciandt.com
lunascar@gmail.com
@lunascarruda
google.com/+LucasArruda
fb.com/lucasnarruda
linkedin.com/in/larruda
github.com/larruda
coderbits.com/larruda
drupal.org/user/1009514

More Related Content

What's hot

Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5 Wildan Maulana
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
Francis Johny
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
Nikita Popov
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
Jason Austin
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010Fabien Potencier
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
Damian T. Gordon
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
Siddhi
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsSunil Kumar Gunasekaran
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 

What's hot (20)

Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 

Viewers also liked

Bastiar
BastiarBastiar
Bastiartiar1
 
BASTIAR LISTENING 10
BASTIAR LISTENING 10BASTIAR LISTENING 10
BASTIAR LISTENING 10tiar1
 
Using natural remedies to treat chronic symptoms
Using natural remedies to treat chronic symptomsUsing natural remedies to treat chronic symptoms
Using natural remedies to treat chronic symptoms
OptimalWellnessLabs
 
What to know about quality of fish oil and parent oil as natrual home remedy
What to know about quality of fish oil and parent oil as natrual home remedyWhat to know about quality of fish oil and parent oil as natrual home remedy
What to know about quality of fish oil and parent oil as natrual home remedy
OptimalWellnessLabs
 
BASTIAR go
BASTIAR goBASTIAR go
BASTIAR gotiar1
 
MKT531 Corporate Branding Gavin Teggart
MKT531 Corporate Branding Gavin TeggartMKT531 Corporate Branding Gavin Teggart
MKT531 Corporate Branding Gavin TeggartGavin Teggart
 
This Is Why We Can't Have Nice Things
This Is Why We Can't Have Nice ThingsThis Is Why We Can't Have Nice Things
This Is Why We Can't Have Nice Things
morganhousel
 
Bab vi bastiar
Bab vi bastiarBab vi bastiar
Bab vi bastiartiar1
 
Pp. dewi ariani bab 6
Pp. dewi ariani bab 6Pp. dewi ariani bab 6
Pp. dewi ariani bab 6dewiarianiaja
 
Pp picture halloween
Pp picture halloweenPp picture halloween
Pp picture halloweendewiarianiaja
 
Selling the Open-Source Philosophy - DrupalCon Latin America
Selling the Open-Source Philosophy - DrupalCon Latin AmericaSelling the Open-Source Philosophy - DrupalCon Latin America
Selling the Open-Source Philosophy - DrupalCon Latin America
Lucas Arruda
 

Viewers also liked (13)

Bastiar
BastiarBastiar
Bastiar
 
1
11
1
 
3
33
3
 
BASTIAR LISTENING 10
BASTIAR LISTENING 10BASTIAR LISTENING 10
BASTIAR LISTENING 10
 
Using natural remedies to treat chronic symptoms
Using natural remedies to treat chronic symptomsUsing natural remedies to treat chronic symptoms
Using natural remedies to treat chronic symptoms
 
What to know about quality of fish oil and parent oil as natrual home remedy
What to know about quality of fish oil and parent oil as natrual home remedyWhat to know about quality of fish oil and parent oil as natrual home remedy
What to know about quality of fish oil and parent oil as natrual home remedy
 
BASTIAR go
BASTIAR goBASTIAR go
BASTIAR go
 
MKT531 Corporate Branding Gavin Teggart
MKT531 Corporate Branding Gavin TeggartMKT531 Corporate Branding Gavin Teggart
MKT531 Corporate Branding Gavin Teggart
 
This Is Why We Can't Have Nice Things
This Is Why We Can't Have Nice ThingsThis Is Why We Can't Have Nice Things
This Is Why We Can't Have Nice Things
 
Bab vi bastiar
Bab vi bastiarBab vi bastiar
Bab vi bastiar
 
Pp. dewi ariani bab 6
Pp. dewi ariani bab 6Pp. dewi ariani bab 6
Pp. dewi ariani bab 6
 
Pp picture halloween
Pp picture halloweenPp picture halloween
Pp picture halloween
 
Selling the Open-Source Philosophy - DrupalCon Latin America
Selling the Open-Source Philosophy - DrupalCon Latin AmericaSelling the Open-Source Philosophy - DrupalCon Latin America
Selling the Open-Source Philosophy - DrupalCon Latin America
 

Similar to 1st CI&T Lightning Talks: Writing better code with Object Calisthenics

Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
Guilherme Blanco
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
Guilherme Blanco
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Lorenzo Dematté
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
潤一 加藤
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
Eugene Zharkov
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
Rafael Dohms
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
Tikal Knowledge
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
Bastian Feder
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
Bernhard Schussek
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 

Similar to 1st CI&T Lightning Talks: Writing better code with Object Calisthenics (20)

Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 

More from Lucas Arruda

Serverless no Google Cloud
Serverless no Google CloudServerless no Google Cloud
Serverless no Google Cloud
Lucas Arruda
 
How to build an ETL pipeline with Apache Beam on Google Cloud Dataflow
How to build an ETL pipeline with Apache Beam on Google Cloud DataflowHow to build an ETL pipeline with Apache Beam on Google Cloud Dataflow
How to build an ETL pipeline with Apache Beam on Google Cloud Dataflow
Lucas Arruda
 
Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015
Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015
Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015
Lucas Arruda
 
InterConPHP 2014 - Scaling PHP
InterConPHP 2014 - Scaling PHPInterConPHP 2014 - Scaling PHP
InterConPHP 2014 - Scaling PHP
Lucas Arruda
 
Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!
Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!
Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!
Lucas Arruda
 
QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...
QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...
QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...
Lucas Arruda
 
PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...
PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...
PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...
Lucas Arruda
 
TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...
TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...
TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...
Lucas Arruda
 

More from Lucas Arruda (8)

Serverless no Google Cloud
Serverless no Google CloudServerless no Google Cloud
Serverless no Google Cloud
 
How to build an ETL pipeline with Apache Beam on Google Cloud Dataflow
How to build an ETL pipeline with Apache Beam on Google Cloud DataflowHow to build an ETL pipeline with Apache Beam on Google Cloud Dataflow
How to build an ETL pipeline with Apache Beam on Google Cloud Dataflow
 
Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015
Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015
Escalando PHP e Drupal: performance ao infinito e além! - DrupalCamp SP 2015
 
InterConPHP 2014 - Scaling PHP
InterConPHP 2014 - Scaling PHPInterConPHP 2014 - Scaling PHP
InterConPHP 2014 - Scaling PHP
 
Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!
Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!
Drupal Day SP 2014 - Virtualize seu Ambiente e Seja Produtivo!
 
QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...
QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...
QCon SP - ShortTalk - Virtualização e Provisionamento de Ambientes com Vagr...
 
PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...
PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...
PHP Conference Brasil 2013 - Virtualização e Provisionamento de Ambientes c...
 
TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...
TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...
TDC2013 - PHP - Virtualização e Provisionamento de Ambientes com Vagrant e ...
 

Recently uploaded

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 

Recently uploaded (20)

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 

1st CI&T Lightning Talks: Writing better code with Object Calisthenics

  • 1. Writing better code with Object Calisthenics Lucas Arruda lucas@ciandt.com github.com/larruda Adapted from Jeff Bay’s paper from “The ThoughtWorks Anthology” and Guilherme Blanco’s presentation.
  • 3.
  • 4. 7 code qualities cohesion loose coupling no redundancy encapsulation testability readability focus
  • 6. 1. One level of indentation per method class Board { ... String board() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) buf.append(data[i][j]); buf.append(“n”); } return buf.toString(); } }
  • 7. 1. One level of indentation per method class Board { ... String Board() { StringBuffer buf = new StringBuffer(); collectRows(buf); return buf.toString(); } void collectRows(StringBuffer buf) { for (int i = 0; i < 10; i++) collectRow(buf, i); } void collectRow(StringBuffer buf, int row) { for (int i = 0; i < 10; i++) Buf.append(data[row][i]); buf.append(“n”); } }
  • 8. 1. One level of indentation per method public function validateForm($filters='', $validators='', $options='') { $data = $_POST; $input = new Zend_Filter_Input($filters, $validators, $data); $input->setDefaultEscapeFilter(new Zend_Filter_StringTrim()); if ($input->hasInvalid() || $input->hasMissing()) { foreach ($input->getMessages() as $field => $messageList) { foreach ($messageList as $message) { if (strpos($message, "empty")) { throw new Tss_FormException( "The field {$field} cannot be empty!", 3, 'javascript:history.back();' ); } else { throw new Tss_FormException( "{$message}", 3, 'javascript:history.back();' ); } } } } return $input; }
  • 9. 1. One level of indentation per method public function validateForm($filters='', $validators='', $options='') { $data = $_POST; $input = new Zend_Filter_Input($filters, $validators, $data); $input->setDefaultEscapeFilter(new Zend_Filter_StringTrim()); if ( ! ($input->hasInvalid() || $input->hasMissing())) { return $input; } foreach ($input->getMessages() as $field => $messageList) { foreach ($messageList as $message) { if (strpos($message, "empty")) { throw new Tss_FormException( "The field {$field} cannot be empty!", 3, 'javascript:history.back();' ); } else { throw new Tss_FormException( "{$message}", 3, 'javascript:history.back();' ); } } } }
  • 10. 1. One level of indentation per method public function validateForm($filters='', $validators='', ... { $data = $_POST; $input = new Zend_Filter_Input ($filters, $validators, $data); $input->setDefaultEscapeFilter( new Zend_Filter_StringTrim ()); if ( ! ($input->hasInvalid() || $input->hasMissing())) { return $input; } foreach ($input->getMessages() as $field => $messageList) { foreach ($messageList as $message) { $errorMessage = (strpos($message, "empty") === false) ? "The field {$field} cannot be empty!" : "{$message}"; throw new Tss_FormException ( $errorMessage, 3, 'javascript:history.back();' ); } } }
  • 11. 1. One level of indentation per method public function validateForm($filters='', $validators='', ... { $data = $_POST; $input = new Zend_Filter_Input ($filters, $validators, $data); $input->setDefaultEscapeFilter( new Zend_Filter_StringTrim ()); if ( ! ($input->hasInvalid() || $input->hasMissing())) { return $input; } foreach ($input->getMessages() as $field => $messageList) { $messageKey = key($message); $message = $message[$messageKey]; $errorMessage = (strpos($message, "empty") === false) ? "The field {$field} cannot be empty!" : "{$message}"; throw new Tss_FormException ( $errorMessage, 3, 'javascript:history.back();' ); } }
  • 12. 2. Don’t use the ELSE keyword if (status == DONE) { doSomething(); } else { … }
  • 14. 2. Don’t use the ELSE keyword class Board { ... String board(StringBuffer buf) { if (buf.length()) { return buf.toString(); } else { collectRows(buf); return buf.toString(); } } ... }
  • 15. 2. Don’t use the ELSE keyword class Board { ... String board(StringBuffer buf) { if (!buf.length()) { collectRows(buf); } return buf.toString(); } ... }
  • 16. 2. Don’t use the ELSE keyword function login() { $login = $this->input->post('email', true); $password = $this->input->post('password', true); $reference = $this->input->post('reference', true); if ($this->clients_model->login($login, $password)) { redirect( $reference); } else { $this->session->set_flashdata( 'error' , 'User or password invalid.' ); $this->session->set_flashdata( 'reference', $reference); redirect( 'clients'); } }
  • 17. 2. Don’t use the ELSE keyword function login() { $login = $this->input->post('email', true); $password = $this->input->post('password', true); $reference = $this->input->post('reference', true); if (!$this->clients_model->login($login, $password)) { $this->session->set_flashdata( 'error' , 'User or password invalid.' ); $this->session->set_flashdata( 'reference', $reference); $reference = 'clients'; } redirect($reference); }
  • 18. 3. Wrap all primitives and Strings
  • 19. If the primitive type has a behavior it should be encapsulated
  • 20. 3. Wrap all primitives and Strings class UIComponent { // ... public function repaint($animate = true) { // … } // ... $component->repaint(false); }
  • 21. 3. Wrap all primitives and Strings class UIComponent { // ... public function repaint(Animate $animate) { // ... } } class Animate { public $animate; public function __construct($animate = true) { $this->animate = $animate; } } // ... $component->repaint(new Animate(false));
  • 22. 4. First class collections Any class that contains a collection/array should not contain any other member variables Java Collections follow this rule
  • 23. 4. First class collections Transversable Countable Iterator Filtering Mapping Combining
  • 24. 5. One dot/arrow per line Sign of misplaced responsibilities The Law of Demeter “Only talk to your friends”
  • 25. 5. One dot/arrow per line class Board { ... class Piece { ... String representation; } class Location { ... Piece current; } String boardRepresentation () { StringBuffer buf = new StringBuffer(); for (Location l: squares()) buf .append(l.current.representation .substring(0, 1)); return buf.toString(); } }
  • 26. 5. One dot/arrow per line class Board { ... class Piece { ... private String representation; String character() { return representation.substring(0, 1); } void addTo(StringBuffer buf) { buf.append(character()); } } class Location { ... private Piece current; void addTo(StringBuffer buf) { current.addTo(buf); } } String boardRepresentation() { StringBuffer buf = new StringBuffer(); for (Location l: squares()) l.addTo(buf); return buf.toString(); } }
  • 27. 6. Don’t abbreviate Are you writing the same name repeatedly? method being used multiple times sign of code duplication Is the method name too long? class with multiple responsibilities missing additional class redundancy
  • 28. 7. Keep all entities small Java No class over 50 lines No packages over 10 files PHP No class over 100 lines No packages over 15 files Packages, like classes, should be cohesive and have a purpose
  • 29. 8. No classes with more than two/five instance variables Improve cohesion Split on more entities
  • 30. 9. No getters/setters/properties Improve encapsulation “Tell, don’t ask”