SlideShare a Scribd company logo
1 of 117
Download to read offline
clean code
There’s no problem so simple that a bad developer
can’t make it complicated. Steve Bohlen
Programming is the art of telling another human what
one wants the computer to do. Donald Knuth
1
warning
A quite not versed rhetorical presenter.
2
warning
A quite not versed rhetorical presenter.
Feel free to interrupt me and ask when something is not clear.
2
warning
A quite not versed rhetorical presenter.
Feel free to interrupt me and ask when something is not clear.
Or something worth discussing.
2
what clean code stands for?
Clean code is a reader-focused development style that produ-
ces software that’s easy to write, read and maintain.
3
why it matters?
Broken windows theory
One broken window is all it takes to start the decline.
4
why it matters?
Broken windows theory
One broken window is all it takes to start the decline.
It’s too easy to slip into the mindset of “All the rest of this code
is crap, I’ll just follow suit.”
4
why it matters?
Broken windows theory
One broken window is all it takes to start the decline.
It’s too easy to slip into the mindset of “All the rest of this code
is crap, I’ll just follow suit.”
It’s the software entropy.
4
why it matters?
Broken windows theory
One broken window is all it takes to start the decline.
It’s too easy to slip into the mindset of “All the rest of this code
is crap, I’ll just follow suit.”
It’s the software entropy.
So called: “software rot.”
4
the four characteristics of rotting software
From the book Design Principles and Design Patterns de Robert
C. Martins
5
1 - rigidity
It’s hard to solve simple problems.
No one knows how long will take to solve them.
Estimating is hard.
6
2 - fragility
The software breaks too often.
A change in one unrelated part breaks others.
Changes must be echoed in many places.
7
3 - immobility
It’s the inability of reusing software from other places.
8
4 - viscosity
Its easier to go to the hacking mode than to the design preser-
vation mode.
9
implications
O preço da gambiarra
10
implications
O preço da gambiarra
Software rot implies in frustrated developers.
10
implications
O preço da gambiarra
Software rot implies in frustrated developers.
Frustrated developers implies in more rotting.
10
implications
O preço da gambiarra
Software rot implies in frustrated developers.
Frustrated developers implies in more rotting.
Too much rooting implies in system rewrite.
10
who’s fault?
Managers
11
who’s fault?
Managers
NOPS
11
who’s fault?
Managers
NOPS
DEVELOPERS
11
who’s fault?
Managers
NOPS
DEVELOPERS
The clinical analogy
11
solution?
Good practices.
Software Wisdom.
Clean code!
Anyone can write code a computer can understand, but profes-
sional developers write code humans can understand.
12
literature
1. Clean code: A hand book of Agile Software craftsmanship;
Robert C. Martin.
2. The pragmatical programmer; Andrew Hunt.
3. Code Complete … Lot’s more
Those who do not remember the past are condemned
to repeat it. Jorge Agustin Nicolas Ruiz de Santayana y
Borras
13
some principles
Dear truth always deceiving simplicity. - John Green
Follow what suites you most.
14
some principles
Dear truth always deceiving simplicity. - John Green
Follow what suites you most.
Obviously this is not an exhaustive list.
14
principle - solid
Or the “first five principles” by Michael Feathers.
15
single responsibility principle
If you can think of more than one motive for changing a class,
then that class has more than one responsibility.
16
open close principle
The interface is closed to modification - and new implementa-
tion must, at least, implement that interface.
17
liskov substitution principle
It’s possible to change subclasses without breaking the pro-
gram.
18
interface segregation principle
It’s better more interfaces than less.
19
dependency inversion
One should depend only on abstractions.
20
principle - dry
Don’t Repeat Yourself
21
principle - dry
Don’t Repeat Yourself
Two or more things are orthogonal if changes in one do not
affect any of the others
21
benefits of orthogonal systems
• Eliminate effects between unrelated things.
• Changes are localized.
• Promotes reuse.
• Disease sections of code are isolated.
• The result system is less fragile.
• Better tested.
• Not tightly to a particular vendor.
22
principle - law of demeter
You don’t ever, ever play with your toy’s toys.
23
principle - law of demeter
You don’t ever, ever 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.
23
principle - composite reuse
One should be build only upon interfaces.
Benefits
• Easier to maintain (no unexpected behaviours);
• Performance gain;
Works flawlessly with traits.
24
//service user
class User
implements AuthenticatedUserAwareInterface,
ClientAwareInterface,
ServiceLocatorAwareInterface,
EntityManagerAwareInterface,
PluginManagerAwareInterface
{
use ClientAwareTrait;
use AuthenticatedUserAwareTrait;
use ServiceLocatorAwareTrait;
use EntityManagerAwareTrait;
use PluginManagerAwareTrait;
25
principle - design by contract
Objects collaborate with each other on the basis of “mutual obli-
gations and benefits”. - Bertrand Meyer
26
principle - design by contract
Objects collaborate with each other on the basis of “mutual obli-
gations and benefits”. - Bertrand Meyer
Developing became the process of honoring contracts. :P
26
principle - design by contract
Objects collaborate with each other on the basis of “mutual obli-
gations and benefits”. - Bertrand Meyer
Developing became the process of honoring contracts. :P
Accept few and promise few.
26
principle - design by contract
Objects collaborate with each other on the basis of “mutual obli-
gations and benefits”. - Bertrand Meyer
Developing became the process of honoring contracts. :P
Accept few and promise few.
If your contract indicates that you’ll accept anything and pro-
mise the world in return, then you’ve got a lot of code to write.
26
principle - the scout rule
Clean code is not about perfection.. It’s about honesty.
27
principle - the scout rule
Clean code is not about perfection.. It’s about honesty.
We made our best to leave the camp cleaner than we find it?
27
practise
Tips for applying the previous principles.
28
functions arguments
The ideal number of arguments of a function is ZERO.
29
functions arguments
The ideal number of arguments of a function is ZERO.
More than tree is unacceptable.
29
functions arguments
The ideal number of arguments of a function is ZERO.
More than tree is unacceptable.
Flag arguments are ugly.
They state a SRP violation.
29
function returns
Output from function is not so good as well.
30
function returns
Output from function is not so good as well.
If functions must change a thing it must change itself.
(Demeter Law)
30
comments - usage scenarios
Put in the dock block at least the authors name.
31
comments - usage scenarios
Put in the dock block at least the authors name.
Attaching responsibility and accountability to the source code
does wonders in keeping people honest.
31
comments - usage scenarios
Put in the dock block at least the authors name.
Attaching responsibility and accountability to the source code
does wonders in keeping people honest.
Comments serves as well to discuss the purpose and trade-offs
of implementations.
31
comments - avoid scenarios
The usual aim of comments is to express the code.
32
comments - avoid scenarios
The usual aim of comments is to express the code.
So, if they are necessary there’s a grand chance that the design
smells.
32
comments - avoid scenarios
The usual aim of comments is to express the code.
So, if they are necessary there’s a grand chance that the design
smells.
Inaccurate comments are way worse than no comments at all.
32
comments - a bad case
/**
*
* @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);
33
comments - a bad case
/**
*
* @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);
Clearly a DRY violation
33
documentation
Code and documentation are different views of the same un-
derlying model.
Two places to edit models? DRY violation.
34
classes - journal metaphor (srp)
Classes should be like journal articles.
35
classes - journal metaphor (srp)
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.
35
classes - journal metaphor (srp)
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.
35
classes - journal metaphor (srp)
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.
A journal is made of many little articles.
35
objects vs data structures
In any good system the distinction of data structures and ob-
jects is clear.
36
objects vs data structures
In any good system the distinction of data structures and ob-
jects is clear.
Objects hide data and expose operations over it.
36
objects vs data structures
In any good system the distinction of data structures and ob-
jects is clear.
Objects hide data and expose operations over it.
Data structures expose data and have no meaningful operation.
36
naming
Long names are generally better and simple names.
Complex operations can be made simple when intermediate va-
riables are used.
37
naming
Long names are generally better and simple names.
Complex operations can be made simple when intermediate va-
riables are used.
Need to see the source for to know what a function does? Work
on names!
37
naming
Long names are generally better and simple names.
Complex operations can be made simple when intermediate va-
riables are used.
Need to see the source for to know what a function does? Work
on names!
If there’s an And in a function name it’s violating SRP.
37
conventions
Follow a coding standard, no matter which, but all the code must
follow the chosen one.
Examples for php
PSR2, Zend, Symphony, etc.
38
many little classes vs few big ones
Some fear to have to browser in many files till find the right
piece of code.
39
many little classes vs few big ones
Some fear to have to browser in many files till find the right
piece of code.
Many classes does not imply in comprehension damage.
39
many little classes vs few big ones
Some fear to have to browser in many files till find the right
piece of code.
Many classes does not imply in comprehension damage.
The Many and the Few approaches both have the same amount
of business logic to care of.
39
many little classes vs few big ones
Some fear to have to browser in many files till find the right
piece of code.
Many classes does not imply in comprehension damage.
The Many and the Few approaches both have the same amount
of business logic to care of.
So the question is:
You prefer your tools being organized in boxes with little com-
partments and good names?
39
many little classes vs few big ones
Some fear to have to browser in many files till find the right
piece of code.
Many classes does not imply in comprehension damage.
The Many and the Few approaches both have the same amount
of business logic to care of.
So the question is:
You prefer your tools being organized in boxes with little com-
partments and good names?
Or only a compartment and all inside?
39
many little classes are always better than few big ones
Any regular system will contain a vast quantity of logic
40
many little classes are always better than few big ones
Any regular system will contain a vast quantity of logic
The first goal of managing complexity is organizing in a way de-
velopers know how to look for a certain thing, without having to
worry about neighbour details.
40
many little classes are always better than few big ones
Any regular system will contain a vast quantity of logic
The first goal of managing complexity is organizing in a way de-
velopers know how to look for a certain thing, without having to
worry about neighbour details.
We want our systems to have many little classes - not few big
ones.
Relates to ISP.
40
abuse of namespaces
InventoryModelTradeStatusType.php
Imagine if we extend this for a long period?
41
Hell!
Bonus.php
BonusRepository.php
BonusType.php
Client.php
ClientRepository.php
ClientSellerLevel.php
Payment.php
PaymentFrequency.php
PaymentMode.php
PaymentStatus.php
Privilege.php
PrivilegeRepository.php
PrivilegeType.php
And so on.. 42
Much better:
InventoryModelTradeStatusType.php
43
remove is better than adding
Perfection is attained not when there is nothing more
to add, but when there is nothing more to remove. An-
toine de Saint-Exupéry
Don’t let existing code dictate future code.
44
remove is better than adding
Perfection is attained not when there is nothing more
to add, but when there is nothing more to remove. An-
toine de Saint-Exupéry
Don’t let existing code dictate future code.
Be ready to refactor.
44
remove is better than adding
Perfection is attained not when there is nothing more
to add, but when there is nothing more to remove. An-
toine de Saint-Exupéry
Don’t let existing code dictate future code.
Be ready to refactor.
It may impact project schedule.
44
remove is better than adding
Perfection is attained not when there is nothing more
to add, but when there is nothing more to remove. An-
toine de Saint-Exupéry
Don’t let existing code dictate future code.
Be ready to refactor.
It may impact project schedule.
The assumption is that the impact will be less than the cost of
not making the change.
44
object calisthenics
Seven code qualities premisses:
• Cohesion;
• Loose coupling;
• No redundancy;
• Encapsulation;
• Testability;
• Readability;
• Focus;
phpcs rules
45
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 abstraction level.
46
2 - don’t use else keyword;
Else’s encourages the inclusion of more, intermediate, ifs.
Use polymorphism instead.
47
3 - wrap all primitives and strings;
Small objects make programs more maintainable.
They serves as a container for logic that otherwise would be
sparse.
48
4 - first class collections
Any class with a collection shouldn’t contain other member va-
riables.
49
5 - one dot per line;
Never:
this
->myMemberObjectMemberObject
->myMemberObjectMemberObject
->doFoo();
Much better:
this
->myMemberObjectMemberObject
->functionThatDoFooToo();
(Law of Demeter)
50
6 - don’t abbreviate;
Abbreviation because of exhaustive use?
51
6 - don’t abbreviate;
Abbreviation because of exhaustive use?
DRY violation.
51
6 - don’t abbreviate;
Abbreviation because of exhaustive use?
DRY violation.
Too long names?
51
6 - don’t abbreviate;
Abbreviation because of exhaustive use?
DRY violation.
Too long names?
Maybe a SRP problem.
51
7 - keep all entities small;
No classes over 50 lines and no packages over 10 files.
52
8 - no classes with more than two instance variables.
A class Name with first, middle and last name might be decom-
posed to:
A class Name with a Surname class and a GivenNames class.
53
9 - no getters/setters/properties
When you have the enough quantity of encapsulation provided
from the previous rules you will never need to do any operation
on the getters/setters.
54
testing clean code
Testing code use different pattens than production code.
They have different constraints.
There things you will never do in production code that in testing
code is allowed.
Like memory and performance things.
55
testing clean code
Testing code use different pattens than production code.
They have different constraints.
There things you will never do in production code that in testing
code is allowed.
Like memory and performance things.
But never clarity things.
55
meta programming
Civilization advances by extending the number of im-
portant operations we can perform without thinking.
Alfred North Whitehead
What we want?
56
meta programming
Civilization advances by extending the number of im-
portant operations we can perform without thinking.
Alfred North Whitehead
What we want?
To go beyond using meta data for simple preferences.
56
meta programming
Civilization advances by extending the number of im-
portant operations we can perform without thinking.
Alfred North Whitehead
What we want?
To go beyond using meta data for simple preferences.
We want to configure and drive the application via meta data as
much as possible.
56
meta programming
Civilization advances by extending the number of im-
portant operations we can perform without thinking.
Alfred North Whitehead
What we want?
To go beyond using meta data for simple preferences.
We want to configure and drive the application via meta data as
much as possible.
Our goal is to think declaratively.
56
meta programming
Civilization advances by extending the number of im-
portant operations we can perform without thinking.
Alfred North Whitehead
What we want?
To go beyond using meta data for simple preferences.
We want to configure and drive the application via meta data as
much as possible.
Our goal is to think declaratively.
And create highly dynamic and adaptable programs.
56
meta programming
Civilization advances by extending the number of im-
portant operations we can perform without thinking.
Alfred North Whitehead
What we want?
To go beyond using meta data for simple preferences.
We want to configure and drive the application via meta data as
much as possible.
Our goal is to think declaratively.
And create highly dynamic and adaptable programs.
How?
56
meta programming
Civilization advances by extending the number of im-
portant operations we can perform without thinking.
Alfred North Whitehead
What we want?
To go beyond using meta data for simple preferences.
We want to configure and drive the application via meta data as
much as possible.
Our goal is to think declaratively.
And create highly dynamic and adaptable programs.
How?
Program for the general case, and put the specifics somewhere
else - outside the code base. 56
metrics
Nice things to measure:
• Ciclomatic complexity;
• Inheritance fan-in (number of base classes);
• Inheritance fan-out (number of derived modules using
this one as parent);
• Class coupling ratios
57
no magic
Never buy magic!
Before you commit to a framework, make sure you could write
it.
58
no magic
Never buy magic!
Before you commit to a framework, make sure you could write
it.
Do this by actually writing something simple that does the ba-
sics that you need.
58
no magic
Never buy magic!
Before you commit to a framework, make sure you could write
it.
Do this by actually writing something simple that does the ba-
sics that you need.
Make sure the magic all goes away.
58
conclusion
Quality is a team issue. Andy hunt.
Teams as a hole should not tolerate broken windows.
59
Obviously no one will ever do the hundred percent of what was
here exposed.
But if we aim for the 80% where code needs the most.
We are cool.
Parts not critical to performance must be clean - not optimized.
60
Remember…
The best programmers are 28 times best than the worst
ones. Robert Glass, Facts and Fallacies of Software En-
gineering
61
Remember…
The best programmers are 28 times best than the worst
ones. Robert Glass, Facts and Fallacies of Software En-
gineering
So there’s always room for improvement.
61
Remember…
The best programmers are 28 times best than the worst
ones. Robert Glass, Facts and Fallacies of Software En-
gineering
So there’s always room for improvement.
Thanks for all!
61

More Related Content

What's hot

Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Asim Rais Siddiqui
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Namenahid035
 
Keep your code clean
Keep your code cleanKeep your code clean
Keep your code cleanmacrochen
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code PrinciplesYeurDreamin'
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summaryJan de Vries
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practicesTan Tran
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
無瑕的程式碼 Clean Code 心得分享
無瑕的程式碼 Clean Code 心得分享無瑕的程式碼 Clean Code 心得分享
無瑕的程式碼 Clean Code 心得分享Win Yu
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 

What's hot (20)

Clean code
Clean codeClean code
Clean code
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Name
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Clean code
Clean code Clean code
Clean code
 
Keep your code clean
Keep your code cleanKeep your code clean
Keep your code clean
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
 
Coding standard
Coding standardCoding standard
Coding standard
 
Clean code
Clean codeClean code
Clean code
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
無瑕的程式碼 Clean Code 心得分享
無瑕的程式碼 Clean Code 心得分享無瑕的程式碼 Clean Code 心得分享
無瑕的程式碼 Clean Code 心得分享
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 

Viewers also liked

Theseus and the_minotaur_pdf2
Theseus and the_minotaur_pdf2Theseus and the_minotaur_pdf2
Theseus and the_minotaur_pdf2Johan Sanchez
 
Third Quarter 2012 Investor Presentation
Third Quarter 2012 Investor PresentationThird Quarter 2012 Investor Presentation
Third Quarter 2012 Investor PresentationCNOServices
 
CarsDirect Internet Sales 20 Group
CarsDirect Internet Sales 20 Group CarsDirect Internet Sales 20 Group
CarsDirect Internet Sales 20 Group Sean Bradley
 
عشر دقائق للقس لبيب مشرقى
عشر دقائق  للقس لبيب مشرقىعشر دقائق  للقس لبيب مشرقى
عشر دقائق للقس لبيب مشرقىIbrahimia Church Ftriends
 
Colònies al castell de fluvià. p5
Colònies al castell de fluvià. p5Colònies al castell de fluvià. p5
Colònies al castell de fluvià. p5escolapigros
 
Scientology VS The Internet
Scientology VS The InternetScientology VS The Internet
Scientology VS The Internetykormes
 
الكتاب المقدس العهد القديم - سفر ارميا
الكتاب المقدس   العهد القديم - سفر ارمياالكتاب المقدس   العهد القديم - سفر ارميا
الكتاب المقدس العهد القديم - سفر ارمياIbrahimia Church Ftriends
 
スティーヴ・ライヒを聴こう
スティーヴ・ライヒを聴こうスティーヴ・ライヒを聴こう
スティーヴ・ライヒを聴こうPrunus 1350
 
Second comingchrist المجىء الثانى للمسبح منيس عبد النور
Second comingchrist المجىء الثانى للمسبح   منيس عبد النورSecond comingchrist المجىء الثانى للمسبح   منيس عبد النور
Second comingchrist المجىء الثانى للمسبح منيس عبد النورIbrahimia Church Ftriends
 
Dasar Fotografi : ISO dan Noise
Dasar Fotografi : ISO dan NoiseDasar Fotografi : ISO dan Noise
Dasar Fotografi : ISO dan NoiseSeggaf Almudhary
 
ابحاث د.لطفي حامد مدكور
ابحاث د.لطفي حامد مدكورابحاث د.لطفي حامد مدكور
ابحاث د.لطفي حامد مدكورAl Baha University
 
Esguince cervical
Esguince cervicalEsguince cervical
Esguince cervicalSky Yaya
 

Viewers also liked (20)

Theseus and the_minotaur_pdf2
Theseus and the_minotaur_pdf2Theseus and the_minotaur_pdf2
Theseus and the_minotaur_pdf2
 
5 November 12
5 November 125 November 12
5 November 12
 
Third Quarter 2012 Investor Presentation
Third Quarter 2012 Investor PresentationThird Quarter 2012 Investor Presentation
Third Quarter 2012 Investor Presentation
 
Svbcrm
SvbcrmSvbcrm
Svbcrm
 
CarsDirect Internet Sales 20 Group
CarsDirect Internet Sales 20 Group CarsDirect Internet Sales 20 Group
CarsDirect Internet Sales 20 Group
 
عشر دقائق للقس لبيب مشرقى
عشر دقائق  للقس لبيب مشرقىعشر دقائق  للقس لبيب مشرقى
عشر دقائق للقس لبيب مشرقى
 
Presentation photo sharing
Presentation photo sharingPresentation photo sharing
Presentation photo sharing
 
02 viga parede
02 viga parede02 viga parede
02 viga parede
 
ظهورات الرب يسوع المسيح
ظهورات الرب يسوع المسيحظهورات الرب يسوع المسيح
ظهورات الرب يسوع المسيح
 
Colònies al castell de fluvià. p5
Colònies al castell de fluvià. p5Colònies al castell de fluvià. p5
Colònies al castell de fluvià. p5
 
Scientology VS The Internet
Scientology VS The InternetScientology VS The Internet
Scientology VS The Internet
 
الكتاب المقدس العهد القديم - سفر ارميا
الكتاب المقدس   العهد القديم - سفر ارمياالكتاب المقدس   العهد القديم - سفر ارميا
الكتاب المقدس العهد القديم - سفر ارميا
 
スティーヴ・ライヒを聴こう
スティーヴ・ライヒを聴こうスティーヴ・ライヒを聴こう
スティーヴ・ライヒを聴こう
 
الشريعه المسيحيه
الشريعه المسيحيهالشريعه المسيحيه
الشريعه المسيحيه
 
Second comingchrist المجىء الثانى للمسبح منيس عبد النور
Second comingchrist المجىء الثانى للمسبح   منيس عبد النورSecond comingchrist المجىء الثانى للمسبح   منيس عبد النور
Second comingchrist المجىء الثانى للمسبح منيس عبد النور
 
Dasar Fotografi : ISO dan Noise
Dasar Fotografi : ISO dan NoiseDasar Fotografi : ISO dan Noise
Dasar Fotografi : ISO dan Noise
 
9 european geo
9 european geo9 european geo
9 european geo
 
ابحاث د.لطفي حامد مدكور
ابحاث د.لطفي حامد مدكورابحاث د.لطفي حامد مدكور
ابحاث د.لطفي حامد مدكور
 
Esguince cervical
Esguince cervicalEsguince cervical
Esguince cervical
 
H.r.m.
H.r.m.H.r.m.
H.r.m.
 

Similar to Clean code

Are You a SOLID Coder?
Are You a SOLID Coder?Are You a SOLID Coder?
Are You a SOLID Coder?Steve Green
 
Git Makes Me Angry Inside - DrupalCon Prague
Git Makes Me Angry Inside - DrupalCon PragueGit Makes Me Angry Inside - DrupalCon Prague
Git Makes Me Angry Inside - DrupalCon PragueEmma Jane Hogbin Westby
 
Bluffers guide to Terminology
Bluffers guide to TerminologyBluffers guide to Terminology
Bluffers guide to TerminologyJim Gough
 
Software craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your teamSoftware craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your teamDattatray Kale
 
Four Patterns at the Heart of Good Programming Style
Four Patterns at the Heart of Good Programming StyleFour Patterns at the Heart of Good Programming Style
Four Patterns at the Heart of Good Programming StylePhilip Schwarz
 
Software Carpentry and the Hydrological Sciences @ AGU 2013
Software Carpentry and the Hydrological Sciences @ AGU 2013Software Carpentry and the Hydrological Sciences @ AGU 2013
Software Carpentry and the Hydrological Sciences @ AGU 2013Aron Ahmadia
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean CodeLuan Reffatti
 
Usable Design Systems with Marti Gold
Usable Design Systems with Marti GoldUsable Design Systems with Marti Gold
Usable Design Systems with Marti GoldSusan Price
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesClean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesAndré de Fontana Ignacio
 
Software quality
Software qualitySoftware quality
Software quality5minpause
 
Software design principles
Software design principlesSoftware design principles
Software design principlesMd.Mojibul Hoque
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering Inocentshuja Ahmad
 
Refactoring 2TheMax (con ReSharper)
Refactoring 2TheMax (con ReSharper)Refactoring 2TheMax (con ReSharper)
Refactoring 2TheMax (con ReSharper)DotNetMarche
 
Finding balance of DDD while your application grows
Finding balance of DDD while your application growsFinding balance of DDD while your application grows
Finding balance of DDD while your application growsCarolina Karklis
 
Solution Architecture and Solution Complexity
Solution Architecture and Solution ComplexitySolution Architecture and Solution Complexity
Solution Architecture and Solution ComplexityAlan McSweeney
 
HeadFirstOOAD_Ch04.ppt
HeadFirstOOAD_Ch04.pptHeadFirstOOAD_Ch04.ppt
HeadFirstOOAD_Ch04.pptCngNguyn725230
 
Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...
Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...
Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...Michael Rosenblum
 
A Timeless Way of Communicating: Alexandrian Pattern Languages
A Timeless Way of Communicating: Alexandrian Pattern LanguagesA Timeless Way of Communicating: Alexandrian Pattern Languages
A Timeless Way of Communicating: Alexandrian Pattern LanguagesJoshua Kerievsky
 

Similar to Clean code (20)

Are You a SOLID Coder?
Are You a SOLID Coder?Are You a SOLID Coder?
Are You a SOLID Coder?
 
Git Makes Me Angry Inside - DrupalCon Prague
Git Makes Me Angry Inside - DrupalCon PragueGit Makes Me Angry Inside - DrupalCon Prague
Git Makes Me Angry Inside - DrupalCon Prague
 
Clean Code V2
Clean Code V2Clean Code V2
Clean Code V2
 
Bluffers guide to Terminology
Bluffers guide to TerminologyBluffers guide to Terminology
Bluffers guide to Terminology
 
Software craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your teamSoftware craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your team
 
Four Patterns at the Heart of Good Programming Style
Four Patterns at the Heart of Good Programming StyleFour Patterns at the Heart of Good Programming Style
Four Patterns at the Heart of Good Programming Style
 
Software Carpentry and the Hydrological Sciences @ AGU 2013
Software Carpentry and the Hydrological Sciences @ AGU 2013Software Carpentry and the Hydrological Sciences @ AGU 2013
Software Carpentry and the Hydrological Sciences @ AGU 2013
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
Usable Design Systems with Marti Gold
Usable Design Systems with Marti GoldUsable Design Systems with Marti Gold
Usable Design Systems with Marti Gold
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesClean code quotes - Citações e provocações
Clean code quotes - Citações e provocações
 
Software quality
Software qualitySoftware quality
Software quality
 
Software design principles
Software design principlesSoftware design principles
Software design principles
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering
 
Code quality
Code quality Code quality
Code quality
 
Refactoring 2TheMax (con ReSharper)
Refactoring 2TheMax (con ReSharper)Refactoring 2TheMax (con ReSharper)
Refactoring 2TheMax (con ReSharper)
 
Finding balance of DDD while your application grows
Finding balance of DDD while your application growsFinding balance of DDD while your application grows
Finding balance of DDD while your application grows
 
Solution Architecture and Solution Complexity
Solution Architecture and Solution ComplexitySolution Architecture and Solution Complexity
Solution Architecture and Solution Complexity
 
HeadFirstOOAD_Ch04.ppt
HeadFirstOOAD_Ch04.pptHeadFirstOOAD_Ch04.ppt
HeadFirstOOAD_Ch04.ppt
 
Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...
Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...
Managing the Earthquake: Surviving Major Database Architecture Changes (rev.2...
 
A Timeless Way of Communicating: Alexandrian Pattern Languages
A Timeless Way of Communicating: Alexandrian Pattern LanguagesA Timeless Way of Communicating: Alexandrian Pattern Languages
A Timeless Way of Communicating: Alexandrian Pattern Languages
 

More from Jean Carlo Machado

More from Jean Carlo Machado (10)

Python clean code for data producs
Python clean code for data producsPython clean code for data producs
Python clean code for data producs
 
Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python
 
Search microservice
Search microserviceSearch microservice
Search microservice
 
Git avançado
Git avançadoGit avançado
Git avançado
 
Functional php
Functional phpFunctional php
Functional php
 
Why functional programming matters
Why functional programming mattersWhy functional programming matters
Why functional programming matters
 
Clean code v3
Clean code v3Clean code v3
Clean code v3
 
Review articles bio inspired algorithms
Review articles bio inspired algorithmsReview articles bio inspired algorithms
Review articles bio inspired algorithms
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
Limitações do HTML no Desenvolvimento de Jogos Multiplataforma
Limitações do HTML no Desenvolvimento de Jogos MultiplataformaLimitações do HTML no Desenvolvimento de Jogos Multiplataforma
Limitações do HTML no Desenvolvimento de Jogos Multiplataforma
 

Recently uploaded

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 

Clean code

  • 1. clean code There’s no problem so simple that a bad developer can’t make it complicated. Steve Bohlen Programming is the art of telling another human what one wants the computer to do. Donald Knuth 1
  • 2. warning A quite not versed rhetorical presenter. 2
  • 3. warning A quite not versed rhetorical presenter. Feel free to interrupt me and ask when something is not clear. 2
  • 4. warning A quite not versed rhetorical presenter. Feel free to interrupt me and ask when something is not clear. Or something worth discussing. 2
  • 5. what clean code stands for? Clean code is a reader-focused development style that produ- ces software that’s easy to write, read and maintain. 3
  • 6. why it matters? Broken windows theory One broken window is all it takes to start the decline. 4
  • 7. why it matters? Broken windows theory One broken window is all it takes to start the decline. It’s too easy to slip into the mindset of “All the rest of this code is crap, I’ll just follow suit.” 4
  • 8. why it matters? Broken windows theory One broken window is all it takes to start the decline. It’s too easy to slip into the mindset of “All the rest of this code is crap, I’ll just follow suit.” It’s the software entropy. 4
  • 9. why it matters? Broken windows theory One broken window is all it takes to start the decline. It’s too easy to slip into the mindset of “All the rest of this code is crap, I’ll just follow suit.” It’s the software entropy. So called: “software rot.” 4
  • 10. the four characteristics of rotting software From the book Design Principles and Design Patterns de Robert C. Martins 5
  • 11. 1 - rigidity It’s hard to solve simple problems. No one knows how long will take to solve them. Estimating is hard. 6
  • 12. 2 - fragility The software breaks too often. A change in one unrelated part breaks others. Changes must be echoed in many places. 7
  • 13. 3 - immobility It’s the inability of reusing software from other places. 8
  • 14. 4 - viscosity Its easier to go to the hacking mode than to the design preser- vation mode. 9
  • 15. implications O preço da gambiarra 10
  • 16. implications O preço da gambiarra Software rot implies in frustrated developers. 10
  • 17. implications O preço da gambiarra Software rot implies in frustrated developers. Frustrated developers implies in more rotting. 10
  • 18. implications O preço da gambiarra Software rot implies in frustrated developers. Frustrated developers implies in more rotting. Too much rooting implies in system rewrite. 10
  • 23. solution? Good practices. Software Wisdom. Clean code! Anyone can write code a computer can understand, but profes- sional developers write code humans can understand. 12
  • 24. literature 1. Clean code: A hand book of Agile Software craftsmanship; Robert C. Martin. 2. The pragmatical programmer; Andrew Hunt. 3. Code Complete … Lot’s more Those who do not remember the past are condemned to repeat it. Jorge Agustin Nicolas Ruiz de Santayana y Borras 13
  • 25. some principles Dear truth always deceiving simplicity. - John Green Follow what suites you most. 14
  • 26. some principles Dear truth always deceiving simplicity. - John Green Follow what suites you most. Obviously this is not an exhaustive list. 14
  • 27. principle - solid Or the “first five principles” by Michael Feathers. 15
  • 28. single responsibility principle If you can think of more than one motive for changing a class, then that class has more than one responsibility. 16
  • 29. open close principle The interface is closed to modification - and new implementa- tion must, at least, implement that interface. 17
  • 30. liskov substitution principle It’s possible to change subclasses without breaking the pro- gram. 18
  • 31. interface segregation principle It’s better more interfaces than less. 19
  • 32. dependency inversion One should depend only on abstractions. 20
  • 33. principle - dry Don’t Repeat Yourself 21
  • 34. principle - dry Don’t Repeat Yourself Two or more things are orthogonal if changes in one do not affect any of the others 21
  • 35. benefits of orthogonal systems • Eliminate effects between unrelated things. • Changes are localized. • Promotes reuse. • Disease sections of code are isolated. • The result system is less fragile. • Better tested. • Not tightly to a particular vendor. 22
  • 36. principle - law of demeter You don’t ever, ever play with your toy’s toys. 23
  • 37. principle - law of demeter You don’t ever, ever 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. 23
  • 38. principle - composite reuse One should be build only upon interfaces. Benefits • Easier to maintain (no unexpected behaviours); • Performance gain; Works flawlessly with traits. 24
  • 39. //service user class User implements AuthenticatedUserAwareInterface, ClientAwareInterface, ServiceLocatorAwareInterface, EntityManagerAwareInterface, PluginManagerAwareInterface { use ClientAwareTrait; use AuthenticatedUserAwareTrait; use ServiceLocatorAwareTrait; use EntityManagerAwareTrait; use PluginManagerAwareTrait; 25
  • 40. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer 26
  • 41. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer Developing became the process of honoring contracts. :P 26
  • 42. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer Developing became the process of honoring contracts. :P Accept few and promise few. 26
  • 43. principle - design by contract Objects collaborate with each other on the basis of “mutual obli- gations and benefits”. - Bertrand Meyer Developing became the process of honoring contracts. :P Accept few and promise few. If your contract indicates that you’ll accept anything and pro- mise the world in return, then you’ve got a lot of code to write. 26
  • 44. principle - the scout rule Clean code is not about perfection.. It’s about honesty. 27
  • 45. principle - the scout rule Clean code is not about perfection.. It’s about honesty. We made our best to leave the camp cleaner than we find it? 27
  • 46. practise Tips for applying the previous principles. 28
  • 47. functions arguments The ideal number of arguments of a function is ZERO. 29
  • 48. functions arguments The ideal number of arguments of a function is ZERO. More than tree is unacceptable. 29
  • 49. functions arguments The ideal number of arguments of a function is ZERO. More than tree is unacceptable. Flag arguments are ugly. They state a SRP violation. 29
  • 50. function returns Output from function is not so good as well. 30
  • 51. function returns Output from function is not so good as well. If functions must change a thing it must change itself. (Demeter Law) 30
  • 52. comments - usage scenarios Put in the dock block at least the authors name. 31
  • 53. comments - usage scenarios Put in the dock block at least the authors name. Attaching responsibility and accountability to the source code does wonders in keeping people honest. 31
  • 54. comments - usage scenarios Put in the dock block at least the authors name. Attaching responsibility and accountability to the source code does wonders in keeping people honest. Comments serves as well to discuss the purpose and trade-offs of implementations. 31
  • 55. comments - avoid scenarios The usual aim of comments is to express the code. 32
  • 56. comments - avoid scenarios The usual aim of comments is to express the code. So, if they are necessary there’s a grand chance that the design smells. 32
  • 57. comments - avoid scenarios The usual aim of comments is to express the code. So, if they are necessary there’s a grand chance that the design smells. Inaccurate comments are way worse than no comments at all. 32
  • 58. comments - a bad case /** * * @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); 33
  • 59. comments - a bad case /** * * @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); Clearly a DRY violation 33
  • 60. documentation Code and documentation are different views of the same un- derlying model. Two places to edit models? DRY violation. 34
  • 61. classes - journal metaphor (srp) Classes should be like journal articles. 35
  • 62. classes - journal metaphor (srp) 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. 35
  • 63. classes - journal metaphor (srp) 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. 35
  • 64. classes - journal metaphor (srp) 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. A journal is made of many little articles. 35
  • 65. objects vs data structures In any good system the distinction of data structures and ob- jects is clear. 36
  • 66. objects vs data structures In any good system the distinction of data structures and ob- jects is clear. Objects hide data and expose operations over it. 36
  • 67. objects vs data structures In any good system the distinction of data structures and ob- jects is clear. Objects hide data and expose operations over it. Data structures expose data and have no meaningful operation. 36
  • 68. naming Long names are generally better and simple names. Complex operations can be made simple when intermediate va- riables are used. 37
  • 69. naming Long names are generally better and simple names. Complex operations can be made simple when intermediate va- riables are used. Need to see the source for to know what a function does? Work on names! 37
  • 70. naming Long names are generally better and simple names. Complex operations can be made simple when intermediate va- riables are used. Need to see the source for to know what a function does? Work on names! If there’s an And in a function name it’s violating SRP. 37
  • 71. conventions Follow a coding standard, no matter which, but all the code must follow the chosen one. Examples for php PSR2, Zend, Symphony, etc. 38
  • 72. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. 39
  • 73. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. 39
  • 74. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. The Many and the Few approaches both have the same amount of business logic to care of. 39
  • 75. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. The Many and the Few approaches both have the same amount of business logic to care of. So the question is: You prefer your tools being organized in boxes with little com- partments and good names? 39
  • 76. many little classes vs few big ones Some fear to have to browser in many files till find the right piece of code. Many classes does not imply in comprehension damage. The Many and the Few approaches both have the same amount of business logic to care of. So the question is: You prefer your tools being organized in boxes with little com- partments and good names? Or only a compartment and all inside? 39
  • 77. many little classes are always better than few big ones Any regular system will contain a vast quantity of logic 40
  • 78. many little classes are always better than few big ones Any regular system will contain a vast quantity of logic The first goal of managing complexity is organizing in a way de- velopers know how to look for a certain thing, without having to worry about neighbour details. 40
  • 79. many little classes are always better than few big ones Any regular system will contain a vast quantity of logic The first goal of managing complexity is organizing in a way de- velopers know how to look for a certain thing, without having to worry about neighbour details. We want our systems to have many little classes - not few big ones. Relates to ISP. 40
  • 80. abuse of namespaces InventoryModelTradeStatusType.php Imagine if we extend this for a long period? 41
  • 83. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. 44
  • 84. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. Be ready to refactor. 44
  • 85. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. Be ready to refactor. It may impact project schedule. 44
  • 86. remove is better than adding Perfection is attained not when there is nothing more to add, but when there is nothing more to remove. An- toine de Saint-Exupéry Don’t let existing code dictate future code. Be ready to refactor. It may impact project schedule. The assumption is that the impact will be less than the cost of not making the change. 44
  • 87. object calisthenics Seven code qualities premisses: • Cohesion; • Loose coupling; • No redundancy; • Encapsulation; • Testability; • Readability; • Focus; phpcs rules 45
  • 88. 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 abstraction level. 46
  • 89. 2 - don’t use else keyword; Else’s encourages the inclusion of more, intermediate, ifs. Use polymorphism instead. 47
  • 90. 3 - wrap all primitives and strings; Small objects make programs more maintainable. They serves as a container for logic that otherwise would be sparse. 48
  • 91. 4 - first class collections Any class with a collection shouldn’t contain other member va- riables. 49
  • 92. 5 - one dot per line; Never: this ->myMemberObjectMemberObject ->myMemberObjectMemberObject ->doFoo(); Much better: this ->myMemberObjectMemberObject ->functionThatDoFooToo(); (Law of Demeter) 50
  • 93. 6 - don’t abbreviate; Abbreviation because of exhaustive use? 51
  • 94. 6 - don’t abbreviate; Abbreviation because of exhaustive use? DRY violation. 51
  • 95. 6 - don’t abbreviate; Abbreviation because of exhaustive use? DRY violation. Too long names? 51
  • 96. 6 - don’t abbreviate; Abbreviation because of exhaustive use? DRY violation. Too long names? Maybe a SRP problem. 51
  • 97. 7 - keep all entities small; No classes over 50 lines and no packages over 10 files. 52
  • 98. 8 - no classes with more than two instance variables. A class Name with first, middle and last name might be decom- posed to: A class Name with a Surname class and a GivenNames class. 53
  • 99. 9 - no getters/setters/properties When you have the enough quantity of encapsulation provided from the previous rules you will never need to do any operation on the getters/setters. 54
  • 100. testing clean code Testing code use different pattens than production code. They have different constraints. There things you will never do in production code that in testing code is allowed. Like memory and performance things. 55
  • 101. testing clean code Testing code use different pattens than production code. They have different constraints. There things you will never do in production code that in testing code is allowed. Like memory and performance things. But never clarity things. 55
  • 102. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? 56
  • 103. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. 56
  • 104. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. 56
  • 105. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. 56
  • 106. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. And create highly dynamic and adaptable programs. 56
  • 107. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. And create highly dynamic and adaptable programs. How? 56
  • 108. meta programming Civilization advances by extending the number of im- portant operations we can perform without thinking. Alfred North Whitehead What we want? To go beyond using meta data for simple preferences. We want to configure and drive the application via meta data as much as possible. Our goal is to think declaratively. And create highly dynamic and adaptable programs. How? Program for the general case, and put the specifics somewhere else - outside the code base. 56
  • 109. metrics Nice things to measure: • Ciclomatic complexity; • Inheritance fan-in (number of base classes); • Inheritance fan-out (number of derived modules using this one as parent); • Class coupling ratios 57
  • 110. no magic Never buy magic! Before you commit to a framework, make sure you could write it. 58
  • 111. no magic Never buy magic! Before you commit to a framework, make sure you could write it. Do this by actually writing something simple that does the ba- sics that you need. 58
  • 112. no magic Never buy magic! Before you commit to a framework, make sure you could write it. Do this by actually writing something simple that does the ba- sics that you need. Make sure the magic all goes away. 58
  • 113. conclusion Quality is a team issue. Andy hunt. Teams as a hole should not tolerate broken windows. 59
  • 114. Obviously no one will ever do the hundred percent of what was here exposed. But if we aim for the 80% where code needs the most. We are cool. Parts not critical to performance must be clean - not optimized. 60
  • 115. Remember… The best programmers are 28 times best than the worst ones. Robert Glass, Facts and Fallacies of Software En- gineering 61
  • 116. Remember… The best programmers are 28 times best than the worst ones. Robert Glass, Facts and Fallacies of Software En- gineering So there’s always room for improvement. 61
  • 117. Remember… The best programmers are 28 times best than the worst ones. Robert Glass, Facts and Fallacies of Software En- gineering So there’s always room for improvement. Thanks for all! 61