SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Downloaden Sie, um offline zu lesen
VictorRentea.ro
1
Clean Code, Two Decades Later
victor.rentea@gmail.com ♦ ♦ @victorrentea ♦ VictorRentea.ro
victorrentea.ro/training-offer
👋 Hi, I'm Victor Rentea 🇷🇴 PhD(CS)
Java Champion, 18 years of code, 10 years of teaching
Consultant & Trainer at 120+ companies:
❤ Clean Code, Architecture, Unit Tes3ng
🛠 Spring, Hibernate, Reac3ve
⚡ Java Performance, Secure Coding
EducaDve Conference Talks on YouTube
Founder of European So<ware Cra<ers Community (6K members)
🔥 Free 1-hour webinars, a;er work 👉 victorrentea.ro/community
Past events on youtube.com/vrentea
Father of 👧👦, servant of a 🐈, weekend gardener 🌼 VictorRentea.ro
3 VictorRentea.ro
a training by
…does one thing well (SRP)
…reads like a story
...was wri3en by someone who cared
Reading a method body does not surprise you
Any fool can write code that a computer understands,
but few programmers know how to write
Clean Code …
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 Programming
COMMUNICATE,
DON’T CODE
code that a human can understand
MOV AX, BX
4 VictorRentea.ro
a training by
International Unit of Measure
for Clean Code ?
wtf/min
Acronyms: What a Terrible Failure, What The Feature
VictorRentea.ro
5
2008
1999 2004
a bit of history...
2019
VictorRentea.ro
6
Many Clean Code rules became Obvious
üDon't copy-paste code (DRY principle)
üMethod size < 1 screen
üA boulean parameter can violate SRP
üComments are not needed by expressive code
üCode forma>ng (team stylesheet)
üImmutability = ❤
Duh!!
VictorRentea.ro
7
FIND 5 DIFFERENCES!
This is code copy-pasted 2 years ago 😨
git blame!
Author left
the team 😞
Ask the
business!
They
forgot 😩
Feature?
(only here must cut it)
Bug?
(forgot to cut it here)
VictorRentea.ro
8
Duplicated Code
Is it a bug or a feature?
DRY
Don't Repeat Yourself
becomes horrible when it changes
Code Smells
Today tools can detect
duplicated code
(IDE, Sonar...)
git blame!
Author left
the team 😞
Ask the
business!
They
forgot 😩
9 VictorRentea.ro
a training by
Where did you learn Clean Code from?
• IDE inspec'ons + Sonar/Linters checking code before commit + on CI
• Construc4ve Code Review by Mandatory PR reviewers
• Pair Programming = faster feedback + human interac'on = 🫶
• Books: Clean Code, Refactoring2nd, or Online Catalog: refactoring.guru
• Uncle Bob's Videos: CleanCoders.com (what got me addicted)
• Refactoring Exercises (kata-log.rocks): imitate > explore > +constraints
( x 2 = 😎 )
10 VictorRentea.ro
a training by
#YOLO Developer
# Don't test your code, just ask someone else to do it.
# It works, so why refactor? It's a waste of time! YOLO!
# I don’t always test my code,
but when I do, I do it in production. YOLO!
# Some fix on SO worked but I don't care why! YOLO
git push --no-verify --force -u master YOLO
You Only Live Once !!
11 VictorRentea.ro
a training by
If you don't care about Clean Code,
welcome to
Legacy Code
12 VictorRentea.ro
a training by
FEAR
833| } // end if (leasePlan = null)
// TODO vrentea 2005-03-21 Temporary hack.
Should be removed befor Prod
if (x!=null && x.y!=null && x.y.z!=null)
// When I wrote this only God and I understood it.
Now, only God knows
12
// not sure if we need this,
but to scared to delete
godMethod(... , boolean param12)
THE DEATH OF YOUR CREATIVITY
13 VictorRentea.ro
a training by
I will cover it with
reliable tests
I will NOT
Ship SH*T
I will not harm
a colleague
A task is NOT DONE unless it's CLEAN and TESTED
VictorRentea.ro
14
Plan
Context
Basic Smells
OO Smells
FP Smells
Mastering Code Smells
is the first step towards
Clean Code mastery
VictorRentea.ro
15
“If it stinks, change it.”
— Grandma Beck, discussing childrearing philosophy
Code Smells
Instinct tells you that
this code will hurt you later
VictorRentea.ro
16
Code Complexity is Always Growing
Code Smells
ß 5 lines of code J
VictorRentea.ro
17
Monster Method God Class Many Parameters
Stuff that grew too big
SRP violation
Code Smells
18 VictorRentea.ro
a training by
Functions Shall be SMALL
SmallerthanaSCREEN!
More complex,
è less lines
The max length should be inversely proportional to the complexity. - Linux coding style guide
≈ 20 lines
... or shorter
19 VictorRentea.ro
a training by
Func%on Length Function Depth
20 VictorRentea.ro
a training by
Flat Func;ons
(linear code with no indentaIon)
21 VictorRentea.ro
a training by
Flat Functions Are Easy to Break into Pieces
22 VictorRentea.ro
a training by
Flat Functions Deeply Nested Func;ons
Most Changes
occur here
Fla2en Code
Huge Cycloma4c/Cogni4ve Complexity
A Sonar metric
23 VictorRentea.ro
a training by
foo bar
§if
- Anemic else {} è flip if🔁 è Guard Clause:
- Superficial if è Split in 2 funcIons è
§for
- è Split Loop è use FP (Stream)
§switch
- ... is alone in a funcIon, with one-line / case
§catch
- è Global ExcepIon Handler
Fla+ening Func0ons
if (param == null) return/throw;
f() {
if (cond) {
foo
} else {
bar
}
}
VictorRentea.ro
24
Monster Method God Class Many Parameters
> 20* lines
*Tweak these numbers for your team comfort
Stuff that grew too big
SRP violation
more complex è shorter
Mul@-line Lambda
-> { ...
Code Smells
è Extract Explanatory Method
Extract only if you can
find a good name
depth > 3*
VictorRentea.ro
25 - extract from a clean code presentation proudly presented to us by a colleague in a workshop
VictorRentea.ro
26
Monster Method God Class Many Parameters
> 200* lines ⛔ > 4* ⛔
*Tweak these numbers for your team comfort
Stuff that grew too big
SRP violation
more complex è shorter
Mul@-line Lambda
-> { ...
è Extract reusable
Parameter Object
Code Smells
è Extract Explanatory Method
è Break method (SRP)
Mixed Layers of AbstracTon
Extract only if you can
find a good name
è Compute one inside
depth > 3*
> 20* lines
VictorRentea.ro
27
OO Smells
VictorRentea.ro
28
Data Clumps
data pieces that stick together
Code Smells
VictorRentea.ro
29
Data Clumps
data pieces that sIck together
(String, String, Integer) è Address
Tuple4<String, Long, Long, LocalDate> è PricedProduct
(in a dynamic language): array, {} è class
Lightweight data structures
Java: @Data/@Value, record
Kotlin: data class
Scala: case class
C#: record class
TS: class, interface, type
Code Smells
aka "Missing AbstracIon"
30 VictorRentea.ro
a training by
Discover New Classes
Simplify Code
safer
Constraints
Spread Logic
OOP
Break Large En77es
Fewer Parameters
and more expressive
PracIce!🏋
VictorRentea.ro
31
Value Objects
è[Small] Immutable
- To change an a*ribute => produce a modified copy
èNo persistent idenFty (PK)
- Lack a "con:nuity of change", unlike En::es
- You cannot say "What part of '3' changed when I set it to '4'?"
èEquals uses all fields (and hashCode)
- Money {10, EUR} equals Money {10, EUR}
* Java Records are good way to implement a VO
VictorRentea.ro
32
!!...
int place = player.getPlace() + roll;
if (place !>= 12) {
place -= 12;
}
player.setPlace(place);
!!...
Data Classes
Data structures that contain only data, no behavior
Feature Envy
Logic operaTng heavily on state of another object
Code Smells
Prefer a Rich Model (DDD) over Anemic Structures:
- Logic inside
- Guarding domain constraints
- Null-safe geZers
OOP
Keep behavior next to state
...should go inside that object
player.advance(roll);
VictorRentea.ro
34
Map<Long, List<Long>> map
Map<Long, List<Long>> customerIdToOrderIds
void redeemCoupon(Long couponId, Long customerId, String phone)
what do these mean?
😨
Code Smells
redeemCoupon(dto.custId, request.cid, request.phone)
Caller:
Primi0ve Obsession
=code full of primitives without semantics
DeclaraTon:
35 VictorRentea.ro
a training by
void redeemCoupon(Long couponId, Long customerId, String phone)
Map<Long, List<Long>> map
redeemCoupon(CustomerId cust, CouponId cup, PhoneNumber p)
Micro-Types
Map<CustomerId, List<OrderId>> orders
class CustomerId {
private final Long id;
...get/hash/equals
}
@lombok.Value
class CouponId {
Long id;
}
You can fight the by creaIng
PrimiTve Obsession
record PhoneNumber(String value){
String getAreaCode() {..}
}
Tuple3<CustomerId, RegionId, List<OrderId>>
Type-safe semanTcs
➖ early decision
➖ surprising
➖ can eat memory
Host bits of logic instead of a UTl
👍 Consider for central IDs
that you aggregate by,
put in Map<X, or Tuples
or extra-complex logic
VictorRentea.ro
36
Functional Programming
VictorRentea.ro
37
Functional Programming
Code Smells
= funcQons are first-class ciQzens
I can directly pass behavior: f( -> ...)
instead of f(new Consumer<X>() { void accept(X x) {...} })
We can avoid mutaQng collecQons
newList = list.stream().filter( ->).map( ->).toList();
VictorRentea.ro
38
Code Smells
<T> Consumer<T> uncheck(ThrowingConsumer<T> f) {
return x -> {
try {
f.accept(x);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}; // what does this do ??!
}
.forEach(uncheck(fileWriter::write)); // caller
Higher-Order Func@ons are HARD
avoid it in non-pure funcIonal languages (like Java)
VictorRentea.ro
39
Functional Programming
FuncQons should be .........
Principles
Objects should be ...................
📽 More in my talk: Pure Func0ons and Immutable Objects
No Side Effects (changes)
Same input è Same output
(adj.)
(adj.)
= Programming without side effects
pure
immutable
VictorRentea.ro
40
VictorRentea.ro
41
Long-Lived Mutable Data
Large Immutable Objects
+ multi-threading = 💀
Immutable Objects
Smaller Immutable Objects
Code Smells
... passed in hard-core flows = 💀
➖ Memory churn (due to cloning)
➖ Harder to trace changes
➖ Heavy Builders
VictorRentea.ro
43
VictorRentea.ro
44
!// sum up all active orders
int sum = 0;
orders.stream() !// stream is cool 😎
.filter(order -> order.isActive())
.forEach(order -> {
sum += order.getPrice();
});
effectively final ( )
(lambdas cannot change local variables on stack)
!// AtomicInteger sum 😱
sum.incrementAndGet(price);
!// int[] sum = {0}; 🤨
sum[0] += price;
!// turn local into field 🤢
this.sum += price;
Hacks: Move accumulator on Heap
Impera@ve FP
In FP: avoid Side Effects!
Code Smells
In FP: Compute and Return ✅
int sum = orders.stream()
.filter(Order!::isActive)
.mapToInt(Order!::getPrice)
.sum();
VictorRentea.ro
45
Impera@ve FP
Code Smells
stream.forEach(e -> ...):void
optional.ifPresent(e -> ...):void
👆 Are code smells if used to accumulate data:
❌ .forEach(e -> map.put(e.id(), e)); è .collect(toMap());
❌ .forEach(e -> adder.increment(e)); è.sum();
❌ .ifPresent(e -> list.add(e)); è .flatMap(OpQonal::stream)
OK to use them for external side effects:
✅ .forEach(m -> mailSender.send(m))
✅ .ifPresent(e -> repo.save(e))
VictorRentea.ro
46
Code Smells
for
VictorRentea.ro
47
Code Smells
Loop
for 😮💨
Phew, I only use
while
VictorRentea.ro
48
Loop
Complex Loop
for (e : list) {
results.add(...)
total += ...
sideEffect(e);
}
Accumulator Loop
var results = new ArrayList();
for (e : list) {
results.add(...)
}
for (e : list) {total += ...}
var total = list.stream()..sum/reduce
for (e : list) sideEffect(e);
Split Loop
Refactoring
var results = list.stream()..collect
Violates SRP gathering data via a loop
Code Smells
🤔
list.forEach(this::sideEffect)
VictorRentea.ro
49
for (e : list) {
a(e);
b(e);
}
Split Loop
Refactoring
= List.of(1,2);
for (e : list) a(e);
for (e : list) b(e);
Thoughts? 🤔
😱 Performance Impact?
= Minimal in BE systems👇
measure it : h9ps://github.com/victorrentea/performance-jmh
⚠ Order of opera4ons changes
from: a(1) b(1) a(2) b(2)
into: a(1) a(2) b(1) b(2)
⚠ Mind the flow breakers:
return, throw, break, continue
VictorRentea.ro
50
List<Product> f() {
return orders.stream()
.filter(o -> o.getCreationDate().isAfter(now().minusYears(1)))
.flatMap(o -> o.getOrderLines().stream())
.collect(groupingBy(OrderLine!::getProduct,
summingInt(OrderLine!::getItemCount)))
.entrySet()
.stream()
.filter(e -> e.getValue() !>= 10)
.map(Entry!::getKey)
.filter(p -> !p.isDeleted())
.filter(p -> !productRepo.findByHiddenTrue().contains(p))
.collect(toList());
}
Code Smells
è extract explanatory
variables and methods
eg. aber every 3-4 operators
⚠ In Reac?ve chains, this is in fact
the recommended coding style
Excessive Chaining
🥇 single-expression funcIons
fun x(..) = ..
VictorRentea.ro
51
@Bean
public Function<Flux<LikeEvent>, Flux<LikedPosts!>> onLikeEvent() {
return flux -> flux
.doOnNext(event -> postLikes.put(event.postId(),event.likes()))
.doOnNext(event -> eventSink.tryEmitNext(event))
.map(LikeEvent!::postId)
.buffer(ofSeconds(1))
.flatMap(ids -> postRepo.findAllById(ids)
.map(Post!::title)
.collectList())
.map(LikedPosts!::new)
.onErrorContinue((x,e) ->log.error(STR."Ignore {x} for {e}"))
.doOnNext(message -> log.info("Sending: " + message));
}
☠ Reac4ve Programming ☠
⚠ In ReacTve chains, this is in fact
the recommended coding style
VictorRentea.ro
52
double average = 0;
for (Employee e : employees) {
average += e.getSalary();
}
average = average / employees.size();
1
2
3
4
5
6
Confused Variable
PRO: Don't reassign local variables
sum
sum
Variables should have a single meaning ✅
Code Smells
consider is ≠ 0
sum
The variable name
is lying at this line
double
here it means "sum" Split Variable: create a separate one
VictorRentea.ro
53
Dead Code
VictorRentea.ro
54
Code Smells
Dead Code
Not Referenced
Grayed out in IDE: param, variable, method
è Safe Delete using IDE = full-text search
⚠ sIll used by reflecIon, clients of your lib...
- Code only called from tests is NOT grayed out
Commented Code
è delete it 👍
è park it on a branch
è feature flag: if (bf) ...
Not Reachable
- Unused API endpoint è Monitor URLs
- Code branch impossible to reach
... you believe 😱😬
è Coverage/Profiler?
⚠ Monitor enough Ime (eg ≥ 13 months)
è If recent, ask author ASAP!!
6 month later: If it works, don't touch it!TM
- Shrink solu7on to minimum when it works
eg aker a SO rampage 🤠
if (<impossible>) {
lots of code
}
VictorRentea.ro
55
Ever wrote code an@cipa@ng
a future possible requirement,
or a broader use (eg a library)?
Code Smells
VictorRentea.ro
56
Overengineering
(SpeculaIve Generality)
è KISS Principle
Keep It Short & Simple
Ever wrote code an-cipa-ng
a future possible requirement,
or a broader use (eg a library)?
Code Smells
Simplicity is the
ul7mate sophis7ca7on
(Leonardo DaVinci)
Nothing is harder than
finding a simple solu?on
to a complex problem.
Yes!
- a bright developer
If that future didn't happen,
did you simplify that code?
😞
VictorRentea.ro
57
Java Language Weaknesses
OpTonal<> @Nullable
null
only throw runTme excepTons
Checked Excep@ons
ImmutableList(Guava)
CollecTons.unmodifiableList() List.of (Java 11) .toList() (Java 17)
Mutable Collec@ons
Code Smells Java got its name by people that had no idea if they were awake or asleep due to coffee abuse.
@Data (Lombok)
geZer, seZer, hash/equals, toString
Boilerplate Code
records (Java 17)
VictorRentea.ro
58
Code Smells
most common today (as of 2023)
Monster Method
God Class
Many Parameters
Heavy Lambda
Flags Data Classes
Data Clumps
PrimiFve Obsession
Feature Envy
Overengineering
Dead Code
ImperaFve FP
Complex Loop
Accumulators
Stream Wreck
Mutable Data
Confused Variable
VictorRentea.ro
59
The End
is this
VictorRentea.ro
60
Schedule right now in your team calendar
your first Ensemble Programming Session,
eg. next Fri, from 16:00 – 18:00
(first hour = office 1me = mandatory)
Ø on a ProducIon code snippet
Ø or a Coding Kata ✔, like:
eg hGps://github.com/victorrentea/kata-trivia-java
eg hGps://kata-log.rocks/refactoring
More about me è victorrentea.ro
The game to play:
• What could someone not like about this code? (idenIfy code smells)
• Ways to fix? (pracIce refactoring moves)
• Tradeoffs? (design principles)
• When NOT to fix? (team reality)
61 VictorRentea.ro
a training by
Refactoring Moves
Extract
InliNe
Method 🌟
Local Variable 🌟
Parameter; also: Change Method Signature
Constant
Interface
Superclass; also: Pull Up to super class
Introduce Parameter Object (eg. Interval)
Move Method / Convert to Instance... (in a param or dependency)
Quick Fix for 300+ inspec'ons (Alt-ENTER)
Rename 👑 ShiR-F6
x
IntelliJ Shortcut:
Win/Lin: Ctrl + Alt + <KEY>
Mac: ⌘ + ⌥ + <KEY>
VictorRentea.ro
Stay into
The Light
Join me: victorrentea.ro/community
sourcemaking.com/refactoring
Chapter 1-11 + 17 Chapter 2+3 + links For Java beginners Coding Katas
kata-log.rocks/refactoring
cleancoders.com
videos that inspire 💗 for code
refactoring.guru
Summary arDcle: link
Clean Code - Reading Guide
A Ime-efficient way to get up to speed with Clean Code and Refactoring
VictorRentea.ro
63
Clean Code, Two Decades Later
victor.rentea@gmail.com ♦ ♦ @victorrentea ♦ VictorRentea.ro
Passionate about Clean Code?
Join our community:

Weitere ähnliche Inhalte

Was ist angesagt?

Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
Victor Rentea
 

Was ist angesagt? (20)

The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User Group
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Integration testing with spring @snow one
Integration testing with spring @snow oneIntegration testing with spring @snow one
Integration testing with spring @snow one
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017Fake It Outside-In TDD @XP2017
Fake It Outside-In TDD @XP2017
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Java開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovyJava開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovy
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design Patterns
 
Software Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdfSoftware Craftsmanship @Code Camp Festival 2022.pdf
Software Craftsmanship @Code Camp Festival 2022.pdf
 
Ksug2015 - JPA3, JPA 내부구조
Ksug2015 - JPA3, JPA 내부구조Ksug2015 - JPA3, JPA 내부구조
Ksug2015 - JPA3, JPA 내부구조
 
[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향
 
Clean Code
Clean CodeClean Code
Clean Code
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 

Ähnlich wie Clean Code @Voxxed Days Cluj 2023 - opening Keynote

Ähnlich wie Clean Code @Voxxed Days Cluj 2023 - opening Keynote (20)

Clean Code - The Next Chapter
Clean Code - The Next ChapterClean Code - The Next Chapter
Clean Code - The Next Chapter
 
Richard wartell malware is hard. let's go shopping!!
Richard wartell   malware is hard.  let's go shopping!!Richard wartell   malware is hard.  let's go shopping!!
Richard wartell malware is hard. let's go shopping!!
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Monitoring a program that monitors computer networks
Monitoring a program that monitors computer networksMonitoring a program that monitors computer networks
Monitoring a program that monitors computer networks
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
How to write clean & testable code without losing your mind
How to write clean & testable code without losing your mindHow to write clean & testable code without losing your mind
How to write clean & testable code without losing your mind
 
Refactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract MethodRefactoring Games - 15 things to do after Extract Method
Refactoring Games - 15 things to do after Extract Method
 
How to be a smart contract engineer
How to be a smart contract engineerHow to be a smart contract engineer
How to be a smart contract engineer
 
refactoring code by clean code rules
refactoring code by clean code rulesrefactoring code by clean code rules
refactoring code by clean code rules
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
Refactoring blockers and code smells @jNation 2021
Refactoring   blockers and code smells @jNation 2021Refactoring   blockers and code smells @jNation 2021
Refactoring blockers and code smells @jNation 2021
 
How to avoid bugs using modern C++
How to avoid bugs using modern C++How to avoid bugs using modern C++
How to avoid bugs using modern C++
 
2018 01-29 - brewbox - refactoring. sempre, senza pietà
2018 01-29 - brewbox - refactoring. sempre, senza pietà2018 01-29 - brewbox - refactoring. sempre, senza pietà
2018 01-29 - brewbox - refactoring. sempre, senza pietà
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
 
Algorithm hierarchy
Algorithm hierarchyAlgorithm hierarchy
Algorithm hierarchy
 

Mehr von Victor Rentea

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Mehr von Victor Rentea (19)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24Microservice Resilience Patterns @VoxxedCern'24
Microservice Resilience Patterns @VoxxedCern'24
 
Distributed Consistency.pdf
Distributed Consistency.pdfDistributed Consistency.pdf
Distributed Consistency.pdf
 
Testing Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdfTesting Microservices @DevoxxBE 23.pdf
Testing Microservices @DevoxxBE 23.pdf
 
From Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptxFrom Web to Flux @DevoxxBE 2023.pptx
From Web to Flux @DevoxxBE 2023.pptx
 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
 
Integration testing with spring @JAX Mainz
Integration testing with spring @JAX MainzIntegration testing with spring @JAX Mainz
Integration testing with spring @JAX Mainz
 
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
The Proxy Fairy and the Magic of Spring @JAX Mainz 2021
 
Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021Pure functions and immutable objects @dev nexus 2021
Pure functions and immutable objects @dev nexus 2021
 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
 
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
Definitive Guide to Working With Exceptions in Java - takj at Java Champions ...
 
Pure Functions and Immutable Objects
Pure Functions and Immutable ObjectsPure Functions and Immutable Objects
Pure Functions and Immutable Objects
 
Definitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in JavaDefinitive Guide to Working With Exceptions in Java
Definitive Guide to Working With Exceptions in Java
 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
 
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
Engaging Isolation - What I've Learned Delivering 250 Webinar Hours during CO...
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
architecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdfarchitecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdf
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements Engineering
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 

Clean Code @Voxxed Days Cluj 2023 - opening Keynote

  • 1. VictorRentea.ro 1 Clean Code, Two Decades Later victor.rentea@gmail.com ♦ ♦ @victorrentea ♦ VictorRentea.ro
  • 2. victorrentea.ro/training-offer 👋 Hi, I'm Victor Rentea 🇷🇴 PhD(CS) Java Champion, 18 years of code, 10 years of teaching Consultant & Trainer at 120+ companies: ❤ Clean Code, Architecture, Unit Tes3ng 🛠 Spring, Hibernate, Reac3ve ⚡ Java Performance, Secure Coding EducaDve Conference Talks on YouTube Founder of European So<ware Cra<ers Community (6K members) 🔥 Free 1-hour webinars, a;er work 👉 victorrentea.ro/community Past events on youtube.com/vrentea Father of 👧👦, servant of a 🐈, weekend gardener 🌼 VictorRentea.ro
  • 3. 3 VictorRentea.ro a training by …does one thing well (SRP) …reads like a story ...was wri3en by someone who cared Reading a method body does not surprise you Any fool can write code that a computer understands, but few programmers know how to write Clean Code … 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 Programming COMMUNICATE, DON’T CODE code that a human can understand MOV AX, BX
  • 4. 4 VictorRentea.ro a training by International Unit of Measure for Clean Code ? wtf/min Acronyms: What a Terrible Failure, What The Feature
  • 6. VictorRentea.ro 6 Many Clean Code rules became Obvious üDon't copy-paste code (DRY principle) üMethod size < 1 screen üA boulean parameter can violate SRP üComments are not needed by expressive code üCode forma>ng (team stylesheet) üImmutability = ❤ Duh!!
  • 7. VictorRentea.ro 7 FIND 5 DIFFERENCES! This is code copy-pasted 2 years ago 😨 git blame! Author left the team 😞 Ask the business! They forgot 😩 Feature? (only here must cut it) Bug? (forgot to cut it here)
  • 8. VictorRentea.ro 8 Duplicated Code Is it a bug or a feature? DRY Don't Repeat Yourself becomes horrible when it changes Code Smells Today tools can detect duplicated code (IDE, Sonar...) git blame! Author left the team 😞 Ask the business! They forgot 😩
  • 9. 9 VictorRentea.ro a training by Where did you learn Clean Code from? • IDE inspec'ons + Sonar/Linters checking code before commit + on CI • Construc4ve Code Review by Mandatory PR reviewers • Pair Programming = faster feedback + human interac'on = 🫶 • Books: Clean Code, Refactoring2nd, or Online Catalog: refactoring.guru • Uncle Bob's Videos: CleanCoders.com (what got me addicted) • Refactoring Exercises (kata-log.rocks): imitate > explore > +constraints ( x 2 = 😎 )
  • 10. 10 VictorRentea.ro a training by #YOLO Developer # Don't test your code, just ask someone else to do it. # It works, so why refactor? It's a waste of time! YOLO! # I don’t always test my code, but when I do, I do it in production. YOLO! # Some fix on SO worked but I don't care why! YOLO git push --no-verify --force -u master YOLO You Only Live Once !!
  • 11. 11 VictorRentea.ro a training by If you don't care about Clean Code, welcome to Legacy Code
  • 12. 12 VictorRentea.ro a training by FEAR 833| } // end if (leasePlan = null) // TODO vrentea 2005-03-21 Temporary hack. Should be removed befor Prod if (x!=null && x.y!=null && x.y.z!=null) // When I wrote this only God and I understood it. Now, only God knows 12 // not sure if we need this, but to scared to delete godMethod(... , boolean param12) THE DEATH OF YOUR CREATIVITY
  • 13. 13 VictorRentea.ro a training by I will cover it with reliable tests I will NOT Ship SH*T I will not harm a colleague A task is NOT DONE unless it's CLEAN and TESTED
  • 14. VictorRentea.ro 14 Plan Context Basic Smells OO Smells FP Smells Mastering Code Smells is the first step towards Clean Code mastery
  • 15. VictorRentea.ro 15 “If it stinks, change it.” — Grandma Beck, discussing childrearing philosophy Code Smells Instinct tells you that this code will hurt you later
  • 16. VictorRentea.ro 16 Code Complexity is Always Growing Code Smells ß 5 lines of code J
  • 17. VictorRentea.ro 17 Monster Method God Class Many Parameters Stuff that grew too big SRP violation Code Smells
  • 18. 18 VictorRentea.ro a training by Functions Shall be SMALL SmallerthanaSCREEN! More complex, è less lines The max length should be inversely proportional to the complexity. - Linux coding style guide ≈ 20 lines ... or shorter
  • 19. 19 VictorRentea.ro a training by Func%on Length Function Depth
  • 20. 20 VictorRentea.ro a training by Flat Func;ons (linear code with no indentaIon)
  • 21. 21 VictorRentea.ro a training by Flat Functions Are Easy to Break into Pieces
  • 22. 22 VictorRentea.ro a training by Flat Functions Deeply Nested Func;ons Most Changes occur here Fla2en Code Huge Cycloma4c/Cogni4ve Complexity A Sonar metric
  • 23. 23 VictorRentea.ro a training by foo bar §if - Anemic else {} è flip if🔁 è Guard Clause: - Superficial if è Split in 2 funcIons è §for - è Split Loop è use FP (Stream) §switch - ... is alone in a funcIon, with one-line / case §catch - è Global ExcepIon Handler Fla+ening Func0ons if (param == null) return/throw; f() { if (cond) { foo } else { bar } }
  • 24. VictorRentea.ro 24 Monster Method God Class Many Parameters > 20* lines *Tweak these numbers for your team comfort Stuff that grew too big SRP violation more complex è shorter Mul@-line Lambda -> { ... Code Smells è Extract Explanatory Method Extract only if you can find a good name depth > 3*
  • 25. VictorRentea.ro 25 - extract from a clean code presentation proudly presented to us by a colleague in a workshop
  • 26. VictorRentea.ro 26 Monster Method God Class Many Parameters > 200* lines ⛔ > 4* ⛔ *Tweak these numbers for your team comfort Stuff that grew too big SRP violation more complex è shorter Mul@-line Lambda -> { ... è Extract reusable Parameter Object Code Smells è Extract Explanatory Method è Break method (SRP) Mixed Layers of AbstracTon Extract only if you can find a good name è Compute one inside depth > 3* > 20* lines
  • 28. VictorRentea.ro 28 Data Clumps data pieces that stick together Code Smells
  • 29. VictorRentea.ro 29 Data Clumps data pieces that sIck together (String, String, Integer) è Address Tuple4<String, Long, Long, LocalDate> è PricedProduct (in a dynamic language): array, {} è class Lightweight data structures Java: @Data/@Value, record Kotlin: data class Scala: case class C#: record class TS: class, interface, type Code Smells aka "Missing AbstracIon"
  • 30. 30 VictorRentea.ro a training by Discover New Classes Simplify Code safer Constraints Spread Logic OOP Break Large En77es Fewer Parameters and more expressive PracIce!🏋
  • 31. VictorRentea.ro 31 Value Objects è[Small] Immutable - To change an a*ribute => produce a modified copy èNo persistent idenFty (PK) - Lack a "con:nuity of change", unlike En::es - You cannot say "What part of '3' changed when I set it to '4'?" èEquals uses all fields (and hashCode) - Money {10, EUR} equals Money {10, EUR} * Java Records are good way to implement a VO
  • 32. VictorRentea.ro 32 !!... int place = player.getPlace() + roll; if (place !>= 12) { place -= 12; } player.setPlace(place); !!... Data Classes Data structures that contain only data, no behavior Feature Envy Logic operaTng heavily on state of another object Code Smells Prefer a Rich Model (DDD) over Anemic Structures: - Logic inside - Guarding domain constraints - Null-safe geZers OOP Keep behavior next to state ...should go inside that object player.advance(roll);
  • 33. VictorRentea.ro 34 Map<Long, List<Long>> map Map<Long, List<Long>> customerIdToOrderIds void redeemCoupon(Long couponId, Long customerId, String phone) what do these mean? 😨 Code Smells redeemCoupon(dto.custId, request.cid, request.phone) Caller: Primi0ve Obsession =code full of primitives without semantics DeclaraTon:
  • 34. 35 VictorRentea.ro a training by void redeemCoupon(Long couponId, Long customerId, String phone) Map<Long, List<Long>> map redeemCoupon(CustomerId cust, CouponId cup, PhoneNumber p) Micro-Types Map<CustomerId, List<OrderId>> orders class CustomerId { private final Long id; ...get/hash/equals } @lombok.Value class CouponId { Long id; } You can fight the by creaIng PrimiTve Obsession record PhoneNumber(String value){ String getAreaCode() {..} } Tuple3<CustomerId, RegionId, List<OrderId>> Type-safe semanTcs ➖ early decision ➖ surprising ➖ can eat memory Host bits of logic instead of a UTl 👍 Consider for central IDs that you aggregate by, put in Map<X, or Tuples or extra-complex logic
  • 36. VictorRentea.ro 37 Functional Programming Code Smells = funcQons are first-class ciQzens I can directly pass behavior: f( -> ...) instead of f(new Consumer<X>() { void accept(X x) {...} }) We can avoid mutaQng collecQons newList = list.stream().filter( ->).map( ->).toList();
  • 37. VictorRentea.ro 38 Code Smells <T> Consumer<T> uncheck(ThrowingConsumer<T> f) { return x -> { try { f.accept(x); } catch (Throwable e) { throw new RuntimeException(e); } }; // what does this do ??! } .forEach(uncheck(fileWriter::write)); // caller Higher-Order Func@ons are HARD avoid it in non-pure funcIonal languages (like Java)
  • 38. VictorRentea.ro 39 Functional Programming FuncQons should be ......... Principles Objects should be ................... 📽 More in my talk: Pure Func0ons and Immutable Objects No Side Effects (changes) Same input è Same output (adj.) (adj.) = Programming without side effects pure immutable
  • 40. VictorRentea.ro 41 Long-Lived Mutable Data Large Immutable Objects + multi-threading = 💀 Immutable Objects Smaller Immutable Objects Code Smells ... passed in hard-core flows = 💀 ➖ Memory churn (due to cloning) ➖ Harder to trace changes ➖ Heavy Builders
  • 42. VictorRentea.ro 44 !// sum up all active orders int sum = 0; orders.stream() !// stream is cool 😎 .filter(order -> order.isActive()) .forEach(order -> { sum += order.getPrice(); }); effectively final ( ) (lambdas cannot change local variables on stack) !// AtomicInteger sum 😱 sum.incrementAndGet(price); !// int[] sum = {0}; 🤨 sum[0] += price; !// turn local into field 🤢 this.sum += price; Hacks: Move accumulator on Heap Impera@ve FP In FP: avoid Side Effects! Code Smells In FP: Compute and Return ✅ int sum = orders.stream() .filter(Order!::isActive) .mapToInt(Order!::getPrice) .sum();
  • 43. VictorRentea.ro 45 Impera@ve FP Code Smells stream.forEach(e -> ...):void optional.ifPresent(e -> ...):void 👆 Are code smells if used to accumulate data: ❌ .forEach(e -> map.put(e.id(), e)); è .collect(toMap()); ❌ .forEach(e -> adder.increment(e)); è.sum(); ❌ .ifPresent(e -> list.add(e)); è .flatMap(OpQonal::stream) OK to use them for external side effects: ✅ .forEach(m -> mailSender.send(m)) ✅ .ifPresent(e -> repo.save(e))
  • 46. VictorRentea.ro 48 Loop Complex Loop for (e : list) { results.add(...) total += ... sideEffect(e); } Accumulator Loop var results = new ArrayList(); for (e : list) { results.add(...) } for (e : list) {total += ...} var total = list.stream()..sum/reduce for (e : list) sideEffect(e); Split Loop Refactoring var results = list.stream()..collect Violates SRP gathering data via a loop Code Smells 🤔 list.forEach(this::sideEffect)
  • 47. VictorRentea.ro 49 for (e : list) { a(e); b(e); } Split Loop Refactoring = List.of(1,2); for (e : list) a(e); for (e : list) b(e); Thoughts? 🤔 😱 Performance Impact? = Minimal in BE systems👇 measure it : h9ps://github.com/victorrentea/performance-jmh ⚠ Order of opera4ons changes from: a(1) b(1) a(2) b(2) into: a(1) a(2) b(1) b(2) ⚠ Mind the flow breakers: return, throw, break, continue
  • 48. VictorRentea.ro 50 List<Product> f() { return orders.stream() .filter(o -> o.getCreationDate().isAfter(now().minusYears(1))) .flatMap(o -> o.getOrderLines().stream()) .collect(groupingBy(OrderLine!::getProduct, summingInt(OrderLine!::getItemCount))) .entrySet() .stream() .filter(e -> e.getValue() !>= 10) .map(Entry!::getKey) .filter(p -> !p.isDeleted()) .filter(p -> !productRepo.findByHiddenTrue().contains(p)) .collect(toList()); } Code Smells è extract explanatory variables and methods eg. aber every 3-4 operators ⚠ In Reac?ve chains, this is in fact the recommended coding style Excessive Chaining 🥇 single-expression funcIons fun x(..) = ..
  • 49. VictorRentea.ro 51 @Bean public Function<Flux<LikeEvent>, Flux<LikedPosts!>> onLikeEvent() { return flux -> flux .doOnNext(event -> postLikes.put(event.postId(),event.likes())) .doOnNext(event -> eventSink.tryEmitNext(event)) .map(LikeEvent!::postId) .buffer(ofSeconds(1)) .flatMap(ids -> postRepo.findAllById(ids) .map(Post!::title) .collectList()) .map(LikedPosts!::new) .onErrorContinue((x,e) ->log.error(STR."Ignore {x} for {e}")) .doOnNext(message -> log.info("Sending: " + message)); } ☠ Reac4ve Programming ☠ ⚠ In ReacTve chains, this is in fact the recommended coding style
  • 50. VictorRentea.ro 52 double average = 0; for (Employee e : employees) { average += e.getSalary(); } average = average / employees.size(); 1 2 3 4 5 6 Confused Variable PRO: Don't reassign local variables sum sum Variables should have a single meaning ✅ Code Smells consider is ≠ 0 sum The variable name is lying at this line double here it means "sum" Split Variable: create a separate one
  • 52. VictorRentea.ro 54 Code Smells Dead Code Not Referenced Grayed out in IDE: param, variable, method è Safe Delete using IDE = full-text search ⚠ sIll used by reflecIon, clients of your lib... - Code only called from tests is NOT grayed out Commented Code è delete it 👍 è park it on a branch è feature flag: if (bf) ... Not Reachable - Unused API endpoint è Monitor URLs - Code branch impossible to reach ... you believe 😱😬 è Coverage/Profiler? ⚠ Monitor enough Ime (eg ≥ 13 months) è If recent, ask author ASAP!! 6 month later: If it works, don't touch it!TM - Shrink solu7on to minimum when it works eg aker a SO rampage 🤠 if (<impossible>) { lots of code }
  • 53. VictorRentea.ro 55 Ever wrote code an@cipa@ng a future possible requirement, or a broader use (eg a library)? Code Smells
  • 54. VictorRentea.ro 56 Overengineering (SpeculaIve Generality) è KISS Principle Keep It Short & Simple Ever wrote code an-cipa-ng a future possible requirement, or a broader use (eg a library)? Code Smells Simplicity is the ul7mate sophis7ca7on (Leonardo DaVinci) Nothing is harder than finding a simple solu?on to a complex problem. Yes! - a bright developer If that future didn't happen, did you simplify that code? 😞
  • 55. VictorRentea.ro 57 Java Language Weaknesses OpTonal<> @Nullable null only throw runTme excepTons Checked Excep@ons ImmutableList(Guava) CollecTons.unmodifiableList() List.of (Java 11) .toList() (Java 17) Mutable Collec@ons Code Smells Java got its name by people that had no idea if they were awake or asleep due to coffee abuse. @Data (Lombok) geZer, seZer, hash/equals, toString Boilerplate Code records (Java 17)
  • 56. VictorRentea.ro 58 Code Smells most common today (as of 2023) Monster Method God Class Many Parameters Heavy Lambda Flags Data Classes Data Clumps PrimiFve Obsession Feature Envy Overengineering Dead Code ImperaFve FP Complex Loop Accumulators Stream Wreck Mutable Data Confused Variable
  • 58. VictorRentea.ro 60 Schedule right now in your team calendar your first Ensemble Programming Session, eg. next Fri, from 16:00 – 18:00 (first hour = office 1me = mandatory) Ø on a ProducIon code snippet Ø or a Coding Kata ✔, like: eg hGps://github.com/victorrentea/kata-trivia-java eg hGps://kata-log.rocks/refactoring More about me è victorrentea.ro The game to play: • What could someone not like about this code? (idenIfy code smells) • Ways to fix? (pracIce refactoring moves) • Tradeoffs? (design principles) • When NOT to fix? (team reality)
  • 59. 61 VictorRentea.ro a training by Refactoring Moves Extract InliNe Method 🌟 Local Variable 🌟 Parameter; also: Change Method Signature Constant Interface Superclass; also: Pull Up to super class Introduce Parameter Object (eg. Interval) Move Method / Convert to Instance... (in a param or dependency) Quick Fix for 300+ inspec'ons (Alt-ENTER) Rename 👑 ShiR-F6 x IntelliJ Shortcut: Win/Lin: Ctrl + Alt + <KEY> Mac: ⌘ + ⌥ + <KEY>
  • 60. VictorRentea.ro Stay into The Light Join me: victorrentea.ro/community sourcemaking.com/refactoring Chapter 1-11 + 17 Chapter 2+3 + links For Java beginners Coding Katas kata-log.rocks/refactoring cleancoders.com videos that inspire 💗 for code refactoring.guru Summary arDcle: link Clean Code - Reading Guide A Ime-efficient way to get up to speed with Clean Code and Refactoring
  • 61. VictorRentea.ro 63 Clean Code, Two Decades Later victor.rentea@gmail.com ♦ ♦ @victorrentea ♦ VictorRentea.ro Passionate about Clean Code? Join our community: