The document discusses clean code principles such as naming conventions, small functions, avoiding nulls and side effects, and using classes as containers for logic. It also emphasizes writing code for readability through techniques like extracting methods, renaming variables for clarity, and using comments to explain intentions rather than restate code. The presenter advocates for clean code as a way to improve code quality and maintainability over time.
1. The Art of Clean Code
= The Next Chapter =
victor.rentea@gmail.com ♦ ♦ @victorrentea ♦ VictorRentea.ro
This is a sequel. Check out the first episode:
“The Art of Clean Code” at Devoxx Poland 2017
12. VictorRentea.ro
…does one thing well
…reads like well written prose
...was written by someone who cared
...when each method you read turns out to be
pretty much what you expected
Any fool can write code that a computer understands,
but few programmers know how to write
Introduction
Clean Code …
14
Bjarne Stroustrup
inventor of C++
Grady Booch
inventor of UML
Michael Feathers
Working Effectively with Legacy Code
Martin Fowler
author of Refactoring
Ward Cunningham
inventor of Wiki, eXtreme Programmingpretty much what you expected
code that a human can understand
MOV AX, BX
14. VictorRentea.ro
code rot
True cost of software = its maintenance
Why so much !?!
Cause we get slower, as the code degrades
Introduction
Why Clean Code ?
16
80% of the total
Code smel
15. VictorRentea.ro
We READ 10x more time than we WRITE
Make it more readable
Boy scout rule
Always check in cleaner code than you found
17
Why Clean Code ?
16. VictorRentea.ro
Simplify* existing code
without changing its external behavior
Refactoring?
18
safe moves
tiny steps
tests
Copy > Make old=useless
Cut > Fix compilation
Built along the way
Use the IDE, Luke!
* simple ≠ easy -> watch “Simple made easy” talk by Rick Hickey
Write down your next
commit message
31. VictorRentea.ro
Classes are nouns
Customer, OrderDetails, OrderFacade
Avoid meaningless names
OrderInfo, OrderData vs Order
Delete the interfaces
ICustomerService, OrderServiceImpl
37
Delete the Interfaces
OrderServiceImpl
OrderDetails OrderSummary
Seek 3-5 options
for any name
32. VictorRentea.ro
… with ONE implementation
in the same module
38
Delete the Interfaces
except:
Remoting/API
your-app-api.jar
Strategy® Pattern
Pick implementation dynamically at runtime
Dependency Inversion
Implemented in lower-level modules
or Decorator®
tomorrow
39. VictorRentea.ro
You found a better name.
48
Make the name speak for itself
It takes seconds with an IDE
(and rarely fails: XMLs, reflection,…)
Rename it !
OMG! It’s impossible!
I CAN’T be smarter
than The Elders!!
48. VictorRentea.ro
A function should do one thing,
it should do it well,
and it should do it ONLY
Functions
62
They should be
Uncle Bob
49. VictorRentea.ro
wtf/min
How small ?
Functions
Functions Should be Smal !!
63
5 lines*
(by any means, smaller than a page of your IDE !)
To be sure that they do just 1 THING
What CAN you do in 5 lines ??
So you CAN find a good name for it
SMALL
Why so small ?!!
* Actually, Uncle Bob now says 5 is too much => extract ‘till you drop
52. VictorRentea.ro
Instead of one familiar landscape,
You’re juggling with dozens of small functions
You can’t even recall all their names
but,
The Team will thank you!
69
else
for if
Scared of small functions?
56. VictorRentea.ro
Overengineering?
a) does too many things ?
Try to introduce a Parameter Object/DTO/VO
Max 3 parameters
74
myBadMethod("John", "Michael", "Paris", "St. Albergue");
address.setStreetName("Paris");
…
myBadMethod(address);
b) just passes down the args ?
?!
… and see how much
code it simplifies
c) common params -> fields [OOP]
58. VictorRentea.ro
Avoid returning null
Throw exception
Wrap it in an Optional<>
Functions
76
Queue
DB
Defensive Programming
Thoroughly check data
only at the boundaries
exception
(corrupt data)
Web
Service
File
null with biz meaning?
Optional<>
62. VictorRentea.ro
do side-effects
return void sendEmail(Email):void
Command-Query Separation
81
setActive(true):void
return results
pure functions
getPrice():int
computePrice(movie):int
More of a guideline than a rule
in 1994, by Bertrand Meyer
63. VictorRentea.ro
No side effects
No INSERTs, JMS, file, fields, WS,…
Idempotent
Same result for same inputs
No random, time, WS, DB…
Pure Functions
82
𝑓 𝑥, 𝑦 = 𝑥2
+ 𝑦
65. VictorRentea.ro
When I write functions, they come out long and complicated.
They have lots of indenting and nested loops.
They have long argument lists.
The names are arbitrary, and there is duplicated code.
I then massage and refine that code, splitting out functions,
changing names, eliminating duplication.
I don’t write them clean from the start.
I don’t think anyone could.
84
~Uncle Bob, in Clean Code
69. VictorRentea.ro
FP
=classes that expose all their state
Data structures
94
public class ImmutableStruct {
private final String firstName;
private final String lastName;
public ImmutableStruct(
String first, String last) {
this.firstName = first;
this.lastName = last;
// validation ...
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
We Immutable Objects:
- If created valid, remain so
- Easier to debug
- Thread safe
- Safe as keys in Tree*/Hash*
struct
≈ Value Object
Pure Function is what
you want to do,
Side Effects are what
you’re being paid to do.
~ “Functional Programming in 40
Minutes” by Russ Olsen at GOTO’18
70. VictorRentea.ro
=classes that expose all their state
Data structures
97
public class PhoneBookEntryDTO {
private String firstName;
private String lastName;
private String phoneNumber;
public String getFirstName() {
return firstName;
}
public void setFirstName(String first) {
this.firstName = first;
}
public String getLastName() { … }
public void setLastName(…) { … }
public String getPhoneNumber() { … }
public void setPhoneNumber(…) { … }
}
public class ImmutableStruct {
private final String firstName;
private final String lastName;
public ImmutableStruct(
String first, String last) {
this.firstName = first;
this.lastName = last;
// validation ...
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
public class PhoneBookEntryDTO {
public String firstName;
public String lastName;
public String phoneNumber;
}
≈
struct
"Object-Oriented
Assembly Language"
72. VictorRentea.ro
Expose Behavior, not data
Data is an implementation detail
OOP
99
car.engineStarted=true
car.setEngineStarted(true)
car.startEngine()
Information Hiding
Even when asked
car.getGasolineInLiters()
car.getPercentageFuelLeft()
car.getEstimatedRemainingKm()
Implementation can evolve
without breaking your clients
73. VictorRentea.ro
100
Protect client code from future changes in implem of a
Library or (mini) Framework
mycorp-commons- .jar
Decompose complex logic into separate objects
Divide-et-impera on Complexity
API
CsvWriter
80. VictorRentea.ro107 Icon made by ‘freepik’ from www.flaticon.com
Procedural
FP
OOP
Encapsulate State
Decompose Side-Effects
Concise
Scalable
Debuggable
86. VictorRentea.ro
Respect your readers
Details matter: 10x more reading, remember ?
Write Literature
The simplest code that works.
Never obfuscate
Don’t Code! Communicate !
Simplicity is the ultimate sophistication
- Leonardo da Vinci
93. VictorRentea.ro142
Clean Code + Java8
Try some lib?
jOOL, vavr,…
For more, check-out the screen cast of my Clean Lambdas workshop
at Voxxed Bucharest 2017, on my website
98. VictorRentea.ro
149
What can I do
to make refactor happen
each day
in my team?
Shamelessly taken from the Effective Refactoring workshop of my friend Wlodek http://refactoring.pl/
109. VictorRentea.ro
When you cannot find a satisfying name for a variable or a method,
Choose a Welsh one.
You won't forget to change it later
- Mario Fusco
114. VictorRentea.ro
Switch Hygiene Rules:
is the only instruction in a method
default: throw new
One-line per case
: return func();
: func(); break;
Coming soon:
return switch …
JEP 325: Switch Expressions
Java 14… soon…
JDD
115. VictorRentea.ro
I'm available
a statement of seniority
I use both hemispheres
Tough meetings?
Abused estimates?
Purpose of code:--Uncle Bob
1. Maintainable
2. Does its job!
Functional Party
Activist
Stay into
The Light
Trainings, talks, goodies
@VictorRentea
Follow me for quality posts:
Clean Code
needs strength
and determination
Thank You!
me take 1 sticker or shortcuts sheet
+
victorrentea.ro/comm
unity
Speaking Romanian? join me
https://github.com/victorrentea/clean-code-dive
Download and customize from victorrentea.ro#stickers
Hunt me for questions!
This talk was a sequel of the first episode:
“The Art of Clean Code” at Devoxx Poland 2017
Editor's Notes
Salut! Eu sunt Victor si am 14 ani… de lucru cu Java, desi in ultimii ani am fost impins sa invat si PHP, Scala si C#.
Lucrez la IBM ca Lead Archirect, in Bucuresti. Stiati voi ca aveti un IBM chiar aici in Cluj, intr-un sediu nou-nout. In….
De fapt, cu ajorul IBM sunt astazi aici cu voi.
Stiu deja ce ganditi… aa.. E architect. Sta undeva langa un ficus si deseneaza pe pereti diagrame UML..
-NU . Eu bag la cod. Lucrez pe cele mai dificile proiecte pe care le avem.
La sfarsh:Sala mare -
nu ne pierdem in detalii: ramanem focusati pe design
nu ne pierdem in detalii: ramanem focusati pe design
Mai mult de 3 parametrii – de unde stii ordinea ?
Mai mult de 3 parametrii – de unde stii ordinea ?
Mai mult de 3 parametrii – de unde stii ordinea ?
Mai mult de 3 parametrii – de unde stii ordinea ?
Mai mult de 3 parametrii – de unde stii ordinea ?
Mai mult de 3 parametrii – de unde stii ordinea ?
Acest curs nu a fost gandit ca un ghid comprehensiv in Design Patterns. Pentru referinte, nuante, clarificari --…
Acest curs nu a fost gandit ca un ghid comprehensiv in Design Patterns. Pentru referinte, nuante, clarificari --…