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

Clean Code V2

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