0% found this document useful (0 votes)
185 views115 pages

Cleancode 191105165842

Uploaded by

Monika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
185 views115 pages

Cleancode 191105165842

Uploaded by

Monika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

This is a sequel.

Check out the first episode:


“The Art of Clean Code” at Devoxx Poland 2017

The Art of Clean Code


= The Next Chapter =
[email protected] ♦ ♦ @victorrentea ♦ VictorRentea.ro
When something is painful
but you can't avoid doing it…

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

Deliberate Practice Code of Ethics


Victor Rentea
Java Champion C#

Lead Architect
Internal Coach

Software Craftsman Founder


Pair Programming, Refactoring, TDD

Clean Code Evangelist


best talks on:
VictorRentea.ro/#playlist
Independent
Technical Trainer & Coach
6 years 1500 devs 30 companies 240+ days
Spring Hibernate Java 8
+ Live-Training on

Design Patterns Architecture, DDD

Clean Code Unit Testing, TDD


Posting daily on
Java Performance Scala more…
30K 3K 2K
[email protected] VictorRentea.ro
VictorRentea.ro @victorrentea [email protected]
Introduction

Clean Code …
Bjarne Stroustrup
…does one thing well inventor of C++

Grady Booch
…reads like well written prose inventor of UML

...was written by someone who cared Michael Feathers


Working Effectively with Legacy Code
...when each method you read turns out to be
Ward Cunningham
pretty much what you expected inventor of Wiki, eXtreme Programming

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 quality meter


15 VictorRentea.ro
Introduction

Why Clean Code ? 80% of the total


True cost of software = its maintenance
Why so much !?!
Code
Cause we get slower, as the code degrades
smel

code rot
16 VictorRentea.ro
Why Clean Code ?
We READ 10x more time than we WRITE
 Make it more readable

Boy scout rule


Always check in cleaner code than you found

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

THE Refactoring Coding Unit Testing


Sprint
19 VictorRentea.ro
Never Separate Them

US-134 US-134 US-134


Refactoring ⊂ Develop
⊃ Unit Tests

20 VictorRentea.ro
21 VictorRentea.ro
22 VictorRentea.ro
What do you do

After the D-day?

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?

31 My trigger was cleancoders.com


VictorRentea.ro
Agenda
Introduction
Names The power that YOU have
Functions
Classes
Formatting & Comments
33 VictorRentea.ro
Names

With Great Power


Comes Great Responsibility
- SpiderMan

34  real author is Uncle Ben VictorRentea.ro


Broca’s Area

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

Delete the Interfaces


interfaces
ICustomerService, OrderServiceImpl
37 VictorRentea.ro
Delete the Interfaces
except: … with ONE implementation
in the same module
Remoting/API
your-app-api.jar

Strategy® Pattern or Decorator®


Pick implementation dynamically at runtime

Dependency Inversion
Implemented in lower-level modules tomorrow

38 VictorRentea.ro
Have you ever blamed some code?

... then find out


YOU were the author?
40 VictorRentea.ro
41 VictorRentea.ro
You Forget

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

Then, you get it!

You change only one line 1 minute

How do you feel?


46 VictorRentea.ro
47 VictorRentea.ro
Make the name speak for itself
You found a better name.
OMG! It’s impossible!
I CAN’T be smarter
than The Elders!!

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(α, β)

VO vo = new VO(α, β);


vo.method();

VictorRentea.ro
Deepen
your Domain Language

VictorRentea.ro
Agenda
Introduction
Names
Functions
Classes
𝑓(𝑥)
Formatting & Comments
61 VictorRentea.ro
Functions

A function should do one thing,


it should do it well,
and it should do it ONLY
Uncle Bob

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 !)

To be sure that they do just 1 THING


wtf/min
What CAN you do in 5 lines ??

So you CAN find a good name for it


63 * Actually, Uncle Bob now says 5 is too much => extract ‘till you drop VictorRentea.ro
EXTRACT METHOD

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

Smaller methods run faster !


(get faster)
Google “Just-In-Time Compiler Optimizations”

67 VictorRentea.ro
Scared of small functions?
Instead of one familiar landscape,
else
for if

You’re juggling with dozens of small functions


You can’t even recall all their names

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");

a) does too many things ?

b) just passes down the args ?


 Try to introduce a Parameter Object/DTO/VO
… and see how much
address.setStreetName("Paris"); code it simplifies

myBadMethod(address); Overengineering?

c) common params -> fields [OOP]


74 VictorRentea.ro
No boolean params => 4
(usually 3)
removeOrders(customer, false, true);
= laziness/fear/rush = legacy

No nullable params => 2


if (customer != null) {…} else {…} What about
invalid data?
,nor Optional<>
75 VictorRentea.ro
Functions

(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);

Because they can


surprise the reader

Side Effects are Evil


but necessary

Make them obvious

80 VictorRentea.ro
do side-effects setActive(true):void

return void sendEmail(Email):void

Command-Query Separation in 1994, by Bertrand Meyer

getPrice():int return results


computePrice(movie):int pure functions

81 More of a guideline than a rule VictorRentea.ro


Pure Functions
No side effects
No INSERTs, JMS, file, fields, WS,…

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.

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. ~Uncle Bob, in Clean Code
84 VictorRentea.ro
The Hat Metaphor
- Kent Beck

Writing Cleaning Unit Testing


Make it Work Make it Readable Crack it

Copy Pasta What can I delete? How can I break it?

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()

Implementation can evolve


without breaking your clients
99 VictorRentea.ro
Protect client code from future changes in implem of a

Library or (mini) Framework

API
mycorp-commons- .jar

Decompose complex logic into separate objects

Divide-et-impera on Complexity
CsvWriter
100 VictorRentea.ro
But at work
we don’t do much OOP, do we ?

In our Enterprise Apps,


we write procedural code

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…

How do we organize it, to


Keep It Short & Simple ?

103 VictorRentea.ro
Procedural Code
Keep It Short & Simple !!

We distribute logic in many classes:

Classes as containers of logic


(in enterprise applications)
104 VictorRentea.ro
Procedural

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

Simplicity is the ultimate sophistication


- Leonardo da Vinci
VictorRentea.ro
117 VictorRentea.ro
Master your IDE
Learn those shortcuts !  Key Promoter X
(IDEA plugin)

Sharpen reflexes for real races


118 VictorRentea.ro
When it's red, yellow, blue or gray,
Ctrl-1
Alt-Enter will save your day.
Ctrl-.

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;

- Name intermediary results


- if (multiline && public
publicList<int[]>
List<Cell> getFlaggedCells(){
getFlaggedCells(){
(conditions || List<int[]>
List<Cell> flaggedCells
flaggedCells == new
new A…L…<…>();
A…L…<Cell>();
formulas)) for
for(int[]
(Cell cell
cell :: gameBoard)
gameBoard) {{
boolean isFlagged= cell[STATUS]==FLAGGED;
Explanatory Methods if (cell.isFlagged())
if (isFlagged)
flaggedCells.add(cell);
- "Encapsulate Conditionals"
} flaggedCells.add(cell);
Rename & Extract } return flaggedCells;

}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

Try some lib?


jOOL, vavr,…

For more, check-out the screen cast of my Clean Lambdas workshop


142 at Voxxed Bucharest 2017, on my website  VictorRentea.ro
Peer Review!
Pair Programming

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(…)

“Keep Behavior next to State”[OOP]


VictorRentea.ro
Most Powerful Forces in Universe

1. Reader

2. Revert

3. Ctrl-
VictorRentea.ro
Do you love switches?

VictorRentea.ro
Switch Hygiene Rules:
is the only instruction in a method

default: throw new JDD

One-line per case


: return func(); Coming soon:
: func(); break; return switch …
JEP 325: Switch Expressions
Java 14… soon… 
VictorRentea.ro
+
Download and customize from victorrentea.ro#stickers
Hunt me for questions!

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?

I use both hemispheres

Speaking Romanian? join me Trainings, talks, goodies Follow me for quality posts:
victorrentea.ro/comm
unity VictorRentea.ro @VictorRentea

You might also like