2. 2
Uncle Bob
Robert Cecil Martin
@unclebobmartin
http://blog.cleancoder.com/
Agile Manifesto, Extreme
Programming, UML for Java...
Clean Coders
3. 3 Warnings
▸ What we’re going to see are
recommendations. They’re not the
Bible. Each case is different and
common sense is above the rules.
▸ There are hundreds (thousands?)
of videos and slides on the topic
https://goo.gl/r25If
▸ It’s the summary of a book
5. 5
Clean Code
A Handbook of Agile Software Craftsmanship
❑ Published in 2008
❑ Summary of known and perceived good practices but not always
implemented
❑ Clean code isn’t just desirable. It is vital for companies and
programmers.
❑ Whoever writes dirty code wastes everyone’s time and money trying to
understand it. Even to his own self.
6. 6
Clean Code
❑ We have the book on paper and in Spanish
❑ On eBook in English
Yeray Darias, Codemotion 2016:
«There are two things that humanity
should not have done: The H-bomb
and the translation of Clean Code»
7. 7
❑ A series of guides and good practices are proposed
when writing code
❑ Examples in Java, but applicable to any high-level
language.
❑ Divided into 2 parts + 1 summary chapter
❑ Caps. 1-13. Good practice
❑ Chaps. 14-16. Examples of real situations
❑ Cap. 17. Odors and symptoms.
8. "The responsibility of doing
good
code belongs to the
programmers. You have to
refuse to do bad code.
9.
10. 9
Clean Code
The clean code is elegant, effective,
readable. With unit tests that explain
what it does and serve as an example
We read more code than we wrote. We
can’t write good code if the one around
is a disaster.
15. 14
Meaningful names
▸ All names have to be descriptive, searchable and
pronunciable. Spend a couple of minutes thinking up a
good name. If you don’t like it, change it later.
▸ Avoid abbreviations, prefixes (Hungarian notation),
redundant words (the- , a- , -object, -data). Use names you
can look for. Avoid single-letter variables (except i, j, k)
▸ Class names start with Shift. The objects with lowercase.
16. 15
Meaningful names
▸ Better to use "added" in the implementation (which will
be private and less used) than in the Interface
(IFactory)
▸ Class names: try to avoid Manager or
Processor
suffixes. Class names should not be verbs, but nouns
▸ Methods: whether they should be verbs
▸ Use get-set and is to access variables
▸ Don’t use puns (which others, perhaps in gitHub and
other cultures) won’t understand or joke.
17. 16
Meaningful names
▸ Use the same words for the same thing. At least
per project (get? fetch? . retrieve?.
▸ Do not use the same word for different things
(is add used to add or to insert?
▸ Use static methods with the name of the
expected argument type instead of multiple
constructors:
19. 18
Meaningful names
▸ Use technical names when the intention is
technical: Factory, List...
▸ If you can’t use a technical name that the next
programmer understands, use one from the
domain (business): at least you can ask someone
from business what it means.
▸ Names, the shorter (although clear and explicit),
the better.
20. 19
Meaningful names
▸ Do not add unnecessary prefixes or contexts:
neg* , GDB* ... Let the IDE help you find
▸ Class CaserEmailAddress. If you need email
elsewhere, will you use that class with that
name?
21. 20
Functions
▸ Two basic rules:
▹ First rule: Reduced: ~ 20 lines
▹ Second rule: Smaller still
▸ Fit on a screen (24 * 80)
▸ That we can describe it in one
sentence
22. 21
Functions
A single level of abstraction in each function: do
not mix high level things with low level.
For example, in an html parser:
▸ A getHtml() call that returns the String
▸ A parseHtml that mixes data sources
▸ A call . append(" n")
▸ Open and close Streams or disk files
24. 23
Functions
▸ They must do only one thing, and do it well. They
should have no side effects: they do what they
are expected to do, and nothing else.
25. 24
boolean?. How do we know
What kind of mistake happened?
public boolean ,String password) {User verifieYPassword( String
user
Incorrect level of abstraction:
Low-level access to BD with
verification of correct data.
enters
boolean = false; Not to mention
we’reif (OracleExecute( "SELECT COUNT(*) FROM USERS WHERE USER='user' AND PASS= 'password'")) {sendin g th e pass wor d...
in
initializeUser Session() ; // We initialize the user’s session clear?
in = true ;
}
return
enters;}
Oracle?. What if
tomorrow is another
BD? Control of errors?
This side effect... Alone
we wanted to verify user and
password!. What if we have to go to
another site to validate the IP or what
sea?
Pointless comment. More on this
later.
Functions
26. 25
Functions
The code should be read as if it were prose, top to
bottom, from greater to lesser abstraction:
public void leemosConfigurationYDetailsUser() {
we read User Representation() & we read User Details();
}
private void leemosDetailsUser() { read DeLdap() details;
}
private void leemosUser() settings{ read
ConfigDeBaseDeDatos();
}
private void readDeLdap() {
}
28. 27
Functions
Integer calculatePaymentEmployed( Employee employee )
{ if( employee.type == Employee.MERCHANT_TYPE 1) {
calculateCommercial payment( int percentage Commission ) ;
} else if ( employee.type == Employee.TRADE_TYPE2 ) {
calculatePayment() + getCommissionFix() ;
} else if ( employee.type == employee.DIRECTIVO_SHAREHOLDER ) {
calculatePaymentADirective( int percentageDeBonus , int
numberDeActions )
;
} else if ( employee.type == employee.MANAGER ) { calculatePayment( int
of the Commission’s share ) ;
} else if ( employee.type == employee.SENORA_LIMIPEZA) {
calculaPagoAGerente( int metrosDeOficina ) ;
} else if (...)
{ } else {
throw exception("Type of invalid employee")
}
}
Problems:
● Does more than one thing
● The list of types could be unlimited
● Breaches the principle of sole
responsibility: there is more than
one reason to change it
● Breach in principle of Open/Closed
("O" SOLID)
● Hypothetically, there could be many
other modules that have this same
if/switch structure
29. 28
Functions
// or Interfaceabstract class Employee{
getSalario()
getDiaDePago()
...
}
class
EmployeesFactory {static Employee created EmployedPorTipo(String type) { switch(type) {
COMMERCIAL CASE: return new Commercial Employment(); case DIRECTOR: return new
EmployedDirective();
case GERENT: return new EmployeedGerente();
}
}
Class EmployedCommercial implements/extends Employee {
Public int getSalario() // real implementation for this type of user. Only this changes if you have to change the
form
}
30. 29
Functions - Method Arguments
▸ There should be no more than 2 parameters. 1 better than 2
▸ 3 are many, and yet must he be justified
▸ Try to avoid (unless just what is expected) changing
parameters within a function. Use the return values.
▸ A parameter should never be boolean. If we have a boolean
we have an if and that means that the function will do at
least two things: do two functions!
31. 30
Functions - Method Arguments
▸ Functions/methods with 2 parameters ok if
related
Point point = makePoint( float x, float y) {
}
}
▸ Can you improve by creating a new
class?
Circle circle = makeCircle( float x, float y, float radio) Circle circle = makeCircle(
Point point, float radio)
32. 31
Functions - Method Arguments
▸ If there are exceptions... throw an exception!. (It doesn’t
have to be processed immediately)
▸ Do not return error codes ( -1, -2 .. ), return an
exception or class containing information
33. 32
Code commentary
▸ There should only be comments when the code is not able to
express what it does.
▸ Acceptable comments
▹ and other legal
▹ Warnings of why a decision has been made
▹ JavaDoc for public APIs
▸ Unacceptable:
▹ Those who tease (contradict the code)
▹ Commented obsolete code just in case one day... Use git!
▹ Reviews of Version History
▹ Those who bring nothing
34. 33
Code commentary
/** * Always returns true.
*/
public boolean isAvailable()
{
return false;
}
return 1; // returns 1
// The day of the month
private int diaDelMes = 0
// somedev1 -
// somedev2 -
6/7/02 Adding temporary tracking of Login
screen
5/22/07 Temporary my ass
try {
....
} catch (Exception e ) {
// something bad has h
}
36. 35
Vertical Format
▸ A class (or procedures file) should not have +200 average lines,
never +500
▸ Metaphor of the newspaper:
▹ A class starts with a descriptive title and no details
▹ Then high-level details
▹ Below low level details
▹ A class is a mixture of more and less long articles
▹ "Headlines" should be understood without having to go into
detail
37. 36
Format
▸ Variables should be declared near their use. Exception: class
variables at the beginning of the class
▸ Width of screen size, better not to scroll
▸ Do not break bleeding even if there is only one line on a block
▸ If one function invokes another, they should be as close as
possible and the caller should be above.
▸ Agree between the team which rules will apply to the entire
code.
The team rules.
38. 37
Format
▸ Avoid excessive nesting. If you even have to put comments
to know closures... is that there is a serious problem.
while ... {
if {
for {
if {
[...]
}
} // for
}
} // while
40. 39
Objects and data structures
▸ The classes, facing the outside, must hide their internal structure
with abstractions that operate on data.
▸ Structures must hide operations and display data
▸ Procedure-oriented code (which uses data structures) facilitates
the inclusion of new functions without modifying existing data
structures.
▸ Object-oriented code facilitates inclusion of new classes without
changing existing functions
41. 40
Objects and data structures
➢ Shapes are data structures, without
behavior. All behavior is in the Geometry
class
➢ If we add a perimeter method the
classes of shapes (and their
descendants) would not be affected
➢ If we add a new form, we have to
change all the methods of the Geometry
class
42. 41
Objects and data structures
➢ Method polymorphic area.
➢ We don’t need a Geometry class, each
class knows for itself how to behave.
➢ If we add a new form, don’t touch
anything from the existing code
➢ But on the other hand, if we add a new
operation (perimeter), we must touch all
the existing forms
43. 42
Objects and data structures
▸ So the opposite is also true:
▸ Procedure-oriented code makes it difficult to include
new data structures (all functions need to be changed)
▸ Object-oriented code makes it difficult to include new functions
because all classes need to be changed.
44. 43
Objects and data structures
▸ Demeter law
▹ A module should not know the interiors of the objects it
manipulates: these must hide their implementation through
operations.
▹A method m of a class C must only invoke:
▹ C
▹ Objects created by m
▹ Objects passed as arguments to m
▹ Instance variable objects of C
46. 45
Objects and data structures
▸ Data Transfer Objects (or, actually, beans)
▹ Data structure (get/sets). With or without representation in
BD
▹ They shouldn’t be behaving.
▸ Special Type: Active Records
▹ More like Grails domain classes
▹ They have save, find...
▹ We may be tempted to add methods with business rules to
them. Error!
48. 47
Mistakes
▸ Use exceptions instead of error
codes
if( conditionError) {
return -1
} else if (otherCondition )
{ return -2
} else {
return 0
}
▸ This forces the caller to immediately verify the condition
49. 48
Mistakes
▸ (Own crop)
▹ Handle only the exceptions you know how to handle. How are
you going to handle a BD connectivity error. Launch it!
▹ Do not gili-
catchs
try{
} catch {
// nothing for here
}
50. 49
Mistakes
▸ Not all exceptions have to be checked. If we do so, we force
everyone who calls to change their class signature to verify.
▸ Sometimes it may be necessary but for example in Groovy the
majority are Unchecked (or runtimeException), as well as only the
catcheas when you need it
▸ Include the context where the exception occurred: let the error
message be informative (we already have the stackTrace)
51. 50
Mistakes
▸ If a third-party bookshop returns us many exceptions it may be
convenient to do a wrapping
▸ Do not return null. It requires constant checks and can easily cause
NPE (running!)
▸ Do not pass null. I’m sure we have an if first. If we want to verify
parameters, it may be good to check that any problem will skip an
InvalidArgumentException, or asserts
53. 52
Limits
▸ Sometimes the system or generic classes are too "big" for what we need
▸ Use them as little as possible as return values in our APIs (what if they
change and ruin something for us?
Map books = new HashMap() Book
book = new Book(...) books.put(
id , book)
…
Book book2 = (Book)books.get(id)
Map<Book> book = new
HashMap<Book>()
54. 53
Limits
Class MapaDeLibros {
private Map books = new HashMap<Book>()
public Book addBook( String key, Book book ){...} public
Book getLibro( String key ){
return books.get(key)
}
// or even old style but at least in a single public site
getLibro book( String key ){
return (Book)books.get(key)
}
}
56. 55
TDD
▸ The concept of TDD did not exist until 1997.
▸ The tests were mini-programs that we then threw away
▸ Laws of TDD
▹ Do not create code until there is a test that fails
▹ The test code has to be the minimum for the production code
to fail
▹ The production code has to be the minimum for the test not to
fail
▸ These rules ensure that the code and tests are created in
57. 56
TDD
▸ Tests are indispensable in modern software development.
▸ Ensure that changes can be made in the future without breaking
anything
▸ These are examples of code usage. Do not ignore seemingly trivial
tests because they are useful as examples
▸ In tests, readability is even more important. Don’t miss the
opportunity to create many variables if it increases readability or
penalizes performance
▸ Avoid very long methods with many implementation details
58. 57
TDD
▸ The tests must be F.I.R.S.T
▹ Fast
▹ Independent
▹ Repeat
▹ Self-Validating
▹ Timely
▸ Not having proof is very bad. But having bad evidence is
worse
▸ The test code is not thrown away: it is as important as the
"real" one.
61. 59
Classes
▸ Order within the class:
▹ Static constants
▹ Static variables
▹ Instance variables
▹ Methods/Functions.
Of all this, first the public and then the
private.
▸ Reduced size
▸ Even smaller size
62. 60
Classes
S.O.L.I.D
▸ Single Responsability
▹ A single (and simple) class liability. Just a reason to change class.
▹ Avoid the "while I’m here, I put this too"
▹ If conceptually what you’re going to do is something else, take it out to another class
▸ Open / Closed
▹ A class must be open to extension but closed to modifications
▹ The most common extension is inheritance, but also the composition can be useful.
▸ Liskov Substitution
▹ A daughter class should be able to use instead of a parent: do not reimplement methods that break up superior
functioning
▸ Interface Segregation
▹ Los interfaces deben tener un sentido concreto y finito: mejor muchos interfaces pequeños a pocos grandes
64. 62
Sistemas
▸ Para dedicar una charla entera (o leerse el capítulo 11 del
libro):
▹ Factorias abstractas
▹ Inyeccion de dependencias
▹ AOP
▹ Proxies
▹ DSL
66. 64
Diseño sencillo
▸ Reglas de Kent Beck para diseño sencillo
▹ Que pase todas las pruebas
▹ No hay codigo duplicado
▹ Expresa la intención del programador
▹ Minimiza el número de clases y métodos
Refactorizar
Hacemos un cambio,
pasa los tests, paramos
un segundo y
pensamos:
¿es mejor que antes?
67. 65
Eliminar duplicados
▸ DRY!
▸ No solo por comodidad: nos ayudan a reducir la complejidad
▸ Ayudan a pensar como mejorar el código
▸ Si tienes buenos test no tienes que tener miedo a romper
nada
68. 66
Expresividad
▸ Cualquier idiota puede hacer código que compila
▸ Solo un buen programador puede hacer código que otros
entiendan
▸ El mayor coste del software es el mantenimiento a largo plazo
▸ Elegir nombres adecuados para metodos, funciones y variables.
70. 68
Concurrencia
▸ Capítulo (13) tambien para dedicarle un tiempo aparte.
▸ Notitas:
▹ Multiproceso no siempre mejora rendimiento: solo si tenemos varios procesadores o máquinas
▹ El diseño del programa cambia si tenemos concurrencia
▹ Muchas veces es mas que conveniente usar objetos inmutables.
▹ Es necesario conocer la infraestructura subyacente (contenedor web, ejbs..)
▹ Saber que clases admiten sincronizacion y cuales no (Hashtable, Hashmap…)
▹ Puede ser conveniente separar el código concurrente del resto. Y que sea lo más pequeño
posible.
▹ Usar colas: Product-Consumer o Publish-Subscribe para desacoplar
▹ Bloqueos: controlar, provocar y prevenir
▹ Si usamos synchronized que sean bloques lo mas pequeños posibles para prevenir deadlocks
71. 69
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
72. 70
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
73. 71
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
74. 72
Suficiente por hoy!
Esto ha sido una introducción.
Recomendación: leeros el libro!. Ved mas videos y
slides
Preguntas?
77. 75
Instructions for use
Open this document in Google Slides (if you are at slidescarnival.com use the button below this presentation)
You have to be signed in to your Google account
EDIT IN GOOGLE
SLIDESGo to the File menu and select Make a
copy. You will get a copy of this document
on your Google Drive and will be able to
edit, add or delete slides.
EDIT IN POWERPOINT®
Go to the File menu and select Download as
Microsoft PowerPoint. You will get a .pptx file that
you can edit in PowerPoint.
Remember to download and install the fonts used in
this presentation (you’ll find the links to the font files
needed in the Presentation design slide)
More info on how to use this template at www.slidescarnival.com/help-use-presentation-template
This template is free to use under Creative Commons Attribution license. You can keep the Credits slide
or mention SlidesCarnival and other resources used in a slide footer.
78. 76
HELLO!
I am Jayden Smith
I am here because I love
to
give presentations. You
can find me at
@username
82. 79
This is a slide title
▸Here you have a list of items
▸And some text
▸But remember not to overload
your slides with content
You audience will listen to you or read
the
content, but won’t do both.
83. 80
BIG CONCEPT
Bring the attention of your audience over
a key concept using icons or illustrations
84. 81
You can also split your content
White
Is the color of milk and
fresh snow, the color
produced by the
combination of all the
colors of the visible
spectrum.
Black
Is the color of coal,
ebony, and of outer
space. It is the darkest
color, the result of the
absence of or complete
absorption of light.
85. 82
In two or three columns
Yellow
Is the color of gold,
butter and ripe
lemons. In the
spectrum of visible
light, yellow is
found between
green and orange.
Blue
Is the colour of the
clear sky and the
deep sea. It is
located between
violet and green
on the optical
spectrum.
Red
Is the color of
blood, and
because of this it
has
historically been
associated with
sacrifice, danger
and courage.
86. 83
A picture is worth a thousand words
A complex idea can be
conveyed with just a single
still image, namely making it
possible to absorb large
amounts of data quickly.
94. 91
Let’s review some concepts
Yellow
Is the color of gold, butter and
ripe lemons. In the spectrum of
visible light, yellow is found
between green and orange.
Blue
Is the colour of the clear sky
and the deep sea. It is located
between violet and green on the
optical spectrum.
Red
Is the color of blood, and
because of this it has historically
been associated with sacrifice,
danger and courage.
Yellow Blue Red
Is the color of gold, butter and Is the colour of the clear sky and Is the color of blood, and
ripe lemons. In the spectrum of the deep sea. It is located because of this it has historically
visible light, yellow is found between violet and green on the been associated with sacrifice,
between green and orange. optical spectrum. danger and courage.
101. 98
Credits
Special thanks to all the people who made
and released these awesome resources for
free:
▸ Presentation template by SlidesCarnival
▸ Photographs by Startupstockphotos
102. 99
Presentation design
This presentation uses the following typographies and colors:
▸ Titles: Dosis
▸ Body copy: Roboto
You can download the fonts on these pages:
https://www.fontsquirrel.com/fonts/dosis
https://material.google.com/resources/roboto-noto-fonts.html
▸ Orange #ff8700
You don’t need to keep this slide in your presentation. It’s only here to serve you as a design
guide if you need to create new slides or download the fonts to edit the presentation in
PowerPoint®
103. 100
SlidesCarnival icons are editable
shapes.
This means that you can:
● Resize them without losing quality.
● Change line color, width and style.
Isn’t that nice? :) Examples:
104. 101
Now you can use any emoji as an icon!
And of course it resizes without losing quality and you can change the color.
How? Follow Google instructions
https://twitter.com/googledocs/status/730087240156643328
✋ ❤
and many more...