Cleancode 191105165842
Cleancode 191105165842
postpone it
When something is painful
but you can't avoid doing it…
delegate it
When something is painful
but you can't avoid doing it…
Do It More Often!
"Bring The Pain Forward!"
Continuous Integration
Pair Programming
Continuous Refactoring
Test-First
e Xtreme
"Bring The Pain Forward!"
Are you Agile ?
Software Craftsmanship
Technical Practices Professionalism
Lead Architect
Internal Coach
Clean Code …
Bjarne Stroustrup
…does one thing well inventor of C++
Grady Booch
…reads like well written prose inventor of UML
Any fool can write code that a computer understands, MOV AX, BX
Martin Fowler
but few programmers know how to write author of Refactoring
code that a human can understand
14 VictorRentea.ro
Unit of Measure
The code is pretty much what you expected
wtf/min
code rot
16 VictorRentea.ro
Why Clean Code ?
We READ 10x more time than we WRITE
Make it more readable
17 VictorRentea.ro
Refactoring?
Simplify* existing code
without changing its external behavior
Copy > Make old=useless safe moves Use the IDE, Luke!
Cut > Fix compilation
tiny steps Write down your next
commit message
Built along the way tests
18 * simple ≠ easy -> watch “Simple made easy” talk by Rick Hickey VictorRentea.ro
US-134 US-134 US-134
Refactoring Unit Tests
Develop
20 VictorRentea.ro
21 VictorRentea.ro
22 VictorRentea.ro
What do you do
VictorRentea.ro
After the D-day?
VictorRentea.ro
After the D-day?
Mob Refactoring
1h
26 VictorRentea.ro
Clean Code
is about
Emotions Team
Attitude
29 VictorRentea.ro
30 VictorRentea.ro
What Will You Choose?
36 VictorRentea.ro
Classes are nouns
Customer, OrderDetails, OrderFacade
Seek 3-5 options
Avoid meaningless names for any name
OrderInfo, OrderData vs Order
OrderDetails OrderSummary
Dependency Inversion
Implemented in lower-level modules tomorrow
38 VictorRentea.ro
Have you ever blamed some code?
42 VictorRentea.ro
You try to understand some code
90% of your work life
45 (in average) VictorRentea.ro
You try to understand some code 2 hours
Rename it !
It takes seconds with an IDE
(and rarely fails: XMLs, reflection,…)
48 VictorRentea.ro
Keep Code Close to Domain
51
the gap VictorRentea.ro
52 Read it for free on: https://leanpub.com/ddd_first_15_years/c/dddeu VictorRentea.ro
More Functions,
Less Names!
53 VictorRentea.ro
54 VictorRentea.ro
VictorRentea.ro
Discover Value Objects
privateMethod(α, β) General-purpose?
Never mocked?
Util1.publicHelper(α, β)
VictorRentea.ro
Deepen
your Domain Language
VictorRentea.ro
Agenda
Introduction
Names
Functions
Classes
𝑓(𝑥)
Formatting & Comments
61 VictorRentea.ro
Functions
They should be
62 VictorRentea.ro
Functions
SMALL
Functions Should be Smal !!
How small ?
Why so small ?!!
5 lines*
(by any means, smaller than a page of your IDE !)
66 VictorRentea.ro
https://www.dailymail.co.uk/home/moslive/article-1198326/TOM-PARKER-BOWLES-How-I-got-caught-Jamie-Olivers-new-cook-food-emporium.html
Performance vs Clean Code
67 VictorRentea.ro
Scared of small functions?
Instead of one familiar landscape,
else
for if
but,
The Team will thank you!
69 VictorRentea.ro
71
https://www.atomicheritage.org/history/security-and-secrecy
Richard Feynman
How to fully redesign
well factored code?
inline everything back
refractor/optimize/redesign
extract again
72 VictorRentea.ro
73
Max 3 parameters ?!
myBadMethod("John", "Michael", "Paris", "St. Albergue");
(corrupt data)
File
Web
Avoid returning null
Service Throw exception
Wrap it in an Optional<>
null with biz meaning?
Defensive Programming
Queue
Thoroughly check data
DB only at the boundaries
76 VictorRentea.ro
Customer.getMemberCard(): Optional<MemberCard>
Game Won!
Entity getters
returning Optional<>
78 VictorRentea.ro
79 https://blog.overops.com/the-top-10-exceptions-types-in-production-java-applications-based-on-1b-events/ VictorRentea.ro
checkAndActivateCustomer(customer,
checkCustomer(customer, order);
wtf/min
customer.setActive(true);
80 VictorRentea.ro
do side-effects setActive(true):void
Idempotent 𝑓 𝑥, 𝑦 = 𝑥 2 + 𝑦
Same result for same inputs
No random, time, WS, DB…
82 VictorRentea.ro
So many guidelines!
83 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.
86 VictorRentea.ro
Agenda
Introduction
Names
Functions
Classes
Formatting & Comments
92 VictorRentea.ro
Do you ever miss
struct
(C language)
93 VictorRentea.ro
Pure Function is what
you want to do, struct
Data structures
Side Effects are what
you’re being paid to do.
=classes that expose all their state
~ “Functional Programming in 40
Minutes” by Russ Olsen at GOTO’18 public class ImmutableStruct {
private final String firstName; ≈ Value Object
private final String lastName;
public ImmutableStruct(
String first, String last) {
this.firstName = first;
FP
this.lastName = last;
// validation ...
} We Immutable Objects:
public String getFirstName() { - If created valid, remain so
return firstName; - Easier to debug
}
public String getLastName() { - Thread safe
return lastName;
}
- Safe as keys in Tree*/Hash*
}
94 VictorRentea.ro
struct
Data structures
=classes that expose all their state
public class ImmutableStruct { public class PhoneBookEntryDTO {
private final String firstName; private String firstName;
private final String lastName; private String lastName;
private String phoneNumber;
public ImmutableStruct(
String first, String last) { public
public String class PhoneBookEntryDTO
getFirstName() { {
≈
this.firstName = first; public String firstName;
return firstName;
this.lastName = last; } public String lastName;
// validation ... public String phoneNumber;
public void setFirstName(String first) {
} }
this.firstName = first;
}
public String getFirstName() { "Object-Oriented
return firstName; public String getLastName() Assembly
{ … } Language"
} public void setLastName(…) { … }
public String getLastName() {
return lastName; public String getPhoneNumber() { … }
} public void setPhoneNumber(…) { … }
} }
97 VictorRentea.ro
OOP
98 VictorRentea.ro
Expose Behavior, not data
Data is an implementation detail
car.engineStarted=true
car.setEngineStarted(true)
car.startEngine()
Information Hiding
OOP Even when asked
car.getGasolineInLiters()
car.getPercentageFuelLeft()
car.getEstimatedRemainingKm()
API
mycorp-commons- .jar
Divide-et-impera on Complexity
CsvWriter
100 VictorRentea.ro
But at work
we don’t do much OOP, do we ?
101 VictorRentea.ro
(usually)
We automate existing business processes.
Existing procedures.
Procedural Code
102 VictorRentea.ro
Procedural Code
Lots and lots and lots and lots and lots of it…
103 VictorRentea.ro
Procedural Code
Keep It Short & Simple !!
OOP FP
105 VictorRentea.ro
106 VictorRentea.ro
Encapsulate State Concise
Decompose Side-Effects Scalable
Debuggable
OOP
FP
Procedural
107 Icon made by ‘freepik’ from www.flaticon.com VictorRentea.ro
Agenda
Introduction
Names
Functions
Classes
Formatting & Comments
110 VictorRentea.ro
112 VictorRentea.ro
113 VictorRentea.ro
You're not Neo
It’s all about Team Work
WAKE UP!
114 VictorRentea.ro
Don’t Code!
Communicate !
115 VictorRentea.ro
Don’t Code! Communicate !
Respect your readers
Details matter: 10x more reading, remember ?
Write Literature
The simplest code that works.
Never obfuscate
120 VictorRentea.ro
Comments
123 VictorRentea.ro
Readable Constants public List<int[]> getCells() {
List<int[]> list1 = new ArrayList<int[]>();
- Instead of magic numbers for (int[] x : theList)
if (x[0] == 4) list1.add(x);
Explanatory Variables }
return list1;
}return flaggedCells;
- descriptive names }
124 VictorRentea.ro
Opinions?
extract DUH!!
// Register user
// Loop over all entries and remove nulls
// Avoids memory leak
129 VictorRentea.ro
Clean Code + Java8
143 VictorRentea.ro
Peer Review!
Pair Programming
144 VictorRentea.ro
Agenda
Introduction
Names
Functions
Classes
Formatting & Comments
Java 8+
147 VictorRentea.ro
Key Points
Agenda
Stop
Introduction
Refactor = Start Legacy
NamesExpressive Names
Refine
Functions
Short methods
Classes Objects or Logic Containers ?
Structs,
Formattingare
Comments & Comments
Failures. Expressive code.
Clean
Pair Lambdas is the way
Programming
148 VictorRentea.ro
What can I do
to make refactor happen
each day
in my team?
149 Shamelessly taken from the Effective Refactoring workshop of my friend Wlodek http://refactoring.pl/ VictorRentea.ro
Pragmatic
+
Where Professional
can I read
LET’S
more ?
How to apply PRACTICE
all this in my !!!
legacy code
??
150 ©
152 VictorRentea.ro
Clean Code
Requires Discipline
153 VictorRentea.ro
Coding Kata
154 VictorRentea.ro
Coding Kata
No rush
Safe environment
Perfection
Reflect on HOW you work
155
Pair Programming
Refactoring
TDD
156 VictorRentea.ro
Synthetic
People Topics Exercises Time
4-10 Refactoring 1-1.5 h
NOT
TDD timeboxed
prod code!!
Legacy Code
Coding Dojo
157 VictorRentea.ro
Blamestorming
Retro
Some learning key points
159 VictorRentea.ro
Rename
&
Extract Method
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
VictorRentea.ro
Extract Method
variable Extract Variables
to generify/reuse
… then extract method
Expand Selection …then inline var back
for less parameters expression
Selection
to Extract
VictorRentea.ro
Feature Envy
method(α, …)
“Move” refactor
α.method(…)
1. Reader
2. Revert
3. Ctrl-
VictorRentea.ro
Do you love switches?
VictorRentea.ro
Switch Hygiene Rules:
is the only instruction in a method
Thank You!
https://github.com/victorrentea/clean-code-dive
This talk was a sequel of the first episode:
“The Art of Clean Code” at Devoxx Poland 2017
me take 1 sticker or shortcuts sheet
Purpose of code:--Uncle Bob Clean Code
Stay into Functional Party 1. Maintainable
I'm available needs strength
The Light Activist 2. Does its job!
a statement of seniority and determination Tough meetings?
Abused estimates?
Speaking Romanian? join me Trainings, talks, goodies Follow me for quality posts:
victorrentea.ro/comm
unity VictorRentea.ro @VictorRentea