SlideShare a Scribd company logo
1 of 51
Download to read offline
victor.rentea@gmail.com โ™ฆ โ™ฆ @victorrentea โ™ฆ VictorRentea.ro
The Hitchhiker Guider to
Victor Rentea
Best Talks, Goodies, Blog:
VictorRentea.ro
Independent Trainer & Consultant
Founder of
Bucharest Software Craftsmanship Community
Java Champion
โค๏ธ Simple Design, Refactoring, Unit Testing โค๏ธ
Technical Training
Hibernate
Spring Func Prog in Java
300+ days
2000 devs
8 years
Training for you or your company: VictorRentea.ro
40 companies
Follow me:
35K 4K 3K
Java Performance
Reactive-X
Design Patterns
Clean Code
Refactoring
Unit Testing
TDD
any
lang
174 ยฉ VictorRentea.ro
a training by
Life
175 ยฉ VictorRentea.ro
a training by
checkCustomer(customer);
checkOrder(customer, order);
Mock-full tests
Race Bugs
A method changes a parameter: Surprise!
Unexpected Different Results for Same Inputs
customer.setActive(true);
Temporal Coupling
176 ยฉ VictorRentea.ro
a training by
do side-effects
return void sendEmail(Email):void
Command-Query Separation
setActive(true):void
return results
search(criteria):List
computePrice(flight):int
in 1994, by Bertrand Meyer
Pure Functions
177 ยฉ VictorRentea.ro
a training by
No side effects
No INSERTs, POSTs, queues, files, fields,โ€ฆ
= ๐‘€๐‘Ž๐‘กโ„Ž๐‘’๐‘š๐‘Ž๐‘ก๐‘–๐‘๐‘Ž๐‘™ ๐น๐‘ข๐‘›๐‘๐‘ก๐‘–๐‘œ๐‘›๐‘ : ๐‘“ ๐‘ฅ, ๐‘ฆ = ๐‘ฅ2
+ ๐‘ฆ
(logging doesn't count)
Referential Transparent
Same Inputs โž” Same Output
No current time, random, GET, SELECTโ€ฆ
โ‰  Idempotent
Pure Functions
178 ยฉ VictorRentea.ro
a training by
Referential Transparent Idempotent
โ‰ 
f(1,2) = 3
f(1,2) can be replaced with 3 everywhere
After calling f once
Calling it again n times
will not produce any extra changes
Can Have Side Effects
eg: DELETE FROM X WHERE ID =
f(1,2)
f(1,2)
f(1,2)
179 ยฉ VictorRentea.ro
a training by
Pure Functions : Quiz
f1(int x) {return x + 1;}
f2(Data d) {return ++d.x;}
f3() {d.incrementX(); return d.x;}
f4() {return querySQL(...);}
f5(int y) { return this.x + y; }
f6(Data d, int y) { return d.getX() + y; }
f7(int i) { if (i<0) throw new WrongInputException(); }
is this immutable?
Probable side effects
Expected to be pure
180 ยฉ VictorRentea.ro
a training by
throw new E(); is pure
f(x) {
try {
//
}
}
catch (E) is pure?
if it always throws for the same inputs
it depends ...
* Some slightly disagree
on E
NO, if E can happen randomly
eg. IOException, OutOfMemory
YES, if E is thrown deterministically*
โž” Catch unexpected exceptions
in the outskirts of your code
181 ยฉ VictorRentea.ro
a training by
Why we Love Pure Functions
โžขNo hidden inputs, only plain-sight return values and parameters
โžขEasier to understand
โžขNo temporal coupling
โžขTestable with less setup
โžขFast & Composable: free to call them n times โž”
โžขParallelizable
(careful with instance functions on mutable objects)
r=f();
a=g(r);
182 ยฉ VictorRentea.ro
a training by
Replace Temp Variable with Query
If a function is pure + fast, it's safe to call it multiple times:
Replace Parameter with Query
var data = f(a,b);
data
data
f(a,b)
f(a,b)
big(..., f(a,b));
param
param
void big(..., param) {
f(a,b)
f(a,b)
they typically are
183 ยฉ VictorRentea.ro
a training by
you don't care how many times
(and if) you call a pure function
184 ยฉ VictorRentea.ro
a training by
185 ยฉ VictorRentea.ro
a training by
That's it!
I'll make all my functions pure
that's usually impossible
What kind of app doesn't change anything?
186 ยฉ VictorRentea.ro
a training by
In Java there's no way to strictly enforce purity
โž” We have to live with both pure and impure functions
How do we distinguish them?
187 ยฉ VictorRentea.ro
a training by
do side-effects
return void sendEmail(Email):void
Command-Query Separation
setActive(true):void
return results
pure functions
search():List
computePrice(movie):int
Highlight Side Effects
computePriceAndAdjustMetrics(movie):int
188 ยฉ VictorRentea.ro
a training by
You can do better!
189 ยฉ VictorRentea.ro
a training by
190 ยฉ VictorRentea.ro
a training by
functional core
Side-effects (Writes) +
Non-deterministic Reads
Expose them
Purify the most complex parts of your logic!
191 ยฉ VictorRentea.ro
a training by
Purify the most complex parts of your logic!
193 ยฉ VictorRentea.ro
a training by
Purifying Logic
Time and Random
Amount of time-dependent logic:
โžขNone (e.setCreationDate(now());) โž” tolerate
โžขVery little โž” Inject a Clock / TimeProvider
โžขHeavy (x-rare) โž” expose a ..., time); parameter
194 ยฉ VictorRentea.ro
a training by
No Files in Functional Core
196 ยฉ VictorRentea.ro
a training by
Initial Read
Intermediary
(conditional?)
โž” Pass as Parameters
โž” Split-Phase Refactor f();
r=read();
f(r);
Writing Results โž” Return Changes w=f();
persist(w);
r=read()
Expose DB and HTTP calls
imperative shell
197 ยฉ VictorRentea.ro
a training by
Expose DB and HTTP calls
Initial Read
Intermediary
(conditional?)
โž” Pass as Parameters
โž” Split-Phase Refactor
r=read();
f(r);
r1=phase1(...)
phase2(r,r1...)
expose impurity
Writing Results โž” Return Changes w=f();
persist(w);
r=read()
imperative shell
Create new classes ๐Ÿ’ช
198 ยฉ VictorRentea.ro
a training by
Implement most complex logic
as internal pure functions
exposing impurity to the surface
199 ยฉ VictorRentea.ro
a training by
Pure Functions don't
Change Objects' State
Immutable Objects
200 ยฉ VictorRentea.ro
a training by
Immutable Objects
201 ยฉ VictorRentea.ro
a training by
void f(Data data) {
...
if (data.getX() == 1) {
// will this run ?
}
}
void h() {
Data data = new Data(1);
obj.setData(data);
g(data);
}
obj
void g(Data data) {
data.setX(2);
mutateParam(data);
obj.mutateField();
f(data);
}
void setData(Data data) {
this.data = data;
}
void mutateField() {
this.data.setX(2);
}
same obj
in h() and g()
void mutateParam(Data data) {
data.setX(1);
}
x=
Long-lived mutable data
A Code Inspection Session
What code ran before,
having a reference
to my data instance?!
Mutable Data
...
...
202 ยฉ VictorRentea.ro
a training by
void f(Data data) {
...
if (data.getX() == 1) {
// will this run ?
}
}
void h() {
Data data = new Data(1);
obj.setData(data);
g(data);
}
obj
void g(Data data) {
data.setX(2);
mutateParam(data);
obj.mutateField();
f(data);
}
void setData(Data data) {
this.data = data;
}
void mutateField() {
this.data.setX(2);
}
same obj
in h() and g()
void mutateParam(Data data) {
data.setX(1);
}
x=
Long-lived mutable data
A Code Inspection Session
What code ran before,
having a reference
to my data instance?!
Mutable Data
Immutable Data
...
...
203 ยฉ VictorRentea.ro
a training by
void f(Data data) {
...
if (data.getX() == 1) {
// will this run ?
}
}
void g(Data data) {
f(data);
}
void h() {
Data data = new Data(1);
g(data);
}
A Code Inspection Session
Immutable Data
Who created
the instance?!
Easier to trace
data changes
x=
204 ยฉ VictorRentea.ro
a training by
Designing Immutable Classes
public class A {
private final String s;
private final B b;
private final List<String> list;
public A(String s, B b, List<String> list) {
this.s = s;
this.b = b;
this.list = new ArrayList<>(list);
// validation ...
}
public List<String> getList() {
return unmodifiableList(list);
}
// getters
// hashCode, equals on all fields = Value Object
// bits of LOGIC ๐Ÿ’ช
public A withS(String newS) {
return new A(newS, b, list);
}
}
Mutates by creating a new instance
Stops creator keeping a reference
Overkill, as problem is not the creator but the "man-in-the-middle"
Oh, so
we CAN mutate them!
@lombok.With
Iterable<String> getList() {
List<? extends String> getList() {
or
final fields,
but not strictly required
record
(java 15)
Java collections are mutable๐Ÿ˜ž
final
Afraid of hackers? ๐Ÿ˜จ
@lombok.Value
or, until then...
205 ยฉ VictorRentea.ro
a training by
Oh, so
we CAN mutate them!
206 ยฉ VictorRentea.ro
a training by
A function changing an immutable object has to return it:
data = updx(data);
Imagine data
has 20 fields
... every time
data = updy(data);
data = updz(data);
The mess is still here!
๐ŸŽต Who changed the field X?
How to fix?
207 ยฉ VictorRentea.ro
a training by
data = updx(data);
data = updy(data);
data = updz(data);
final variables won't allow this
IntelliJ underlines
reassigned variables โค๏ธ
By the way, there are ways to add final automatically at code cleanup
Real Problem
Too Large Immutable Objects
data.xyz = createXYZ(...);
โž” break them
If they change together,
they stick together
= clutter; Extreme:
Mark only the non-final with @Var
(errorprone Java compiler from Google)
208 ยฉ VictorRentea.ro
a training by
Wait a second,
I know...
209 ยฉ VictorRentea.ro
a training by
void f(VO[] arr) {
arr[0] = arr[0].withX(-99);
}
void f(List<String> list) {
list.removeIf(String::isBlank);
}
void f(Map<Integer, VO> map) {
map.put(1, map.get(1).withX(-99));
}
map.get(1).withX(-99)
210 ยฉ VictorRentea.ro
a training by
Don't
ever
mutate
collections!
โž” Create new ones
211 ยฉ VictorRentea.ro
a training by
Why we Immutable objects
Easier to trace data changes
Can enforce validation in constructor
Safe to put in Set or Map(as keys)
Thread-safe โž” no race bugs, since they can't be changed
โž” their hashCode
doesn't change
212 ยฉ VictorRentea.ro
a training by
All right cowboy!
Only immutable objects from now on!
usually that's too much!
214 ยฉ VictorRentea.ro
a training by
instead,
Extract immutable Value Objects from their fields
Leaving the root Entity mutable
NO*
*there are few cases when it pays to, but those apps typically don't persist their data
Should Entities be immutable?
215 ยฉ VictorRentea.ro
a training by
@Entity
(mutable)
Persistent
Immutable Leaf
eg. FullName
Immutable Objects in Real Life
Non-Persistent
Runtime Objects
that you write heavy logic with
continuously break
Large Entities
@Embeddable
216 ยฉ VictorRentea.ro
a training by
Non-Persistent
Runtime Objects
that you write heavy logic with
Always Immutable
218 ยฉ VictorRentea.ro
a training by
The Big Deal
219 ยฉ VictorRentea.ro
a training by
The Big Deal
Don't mutate objects on long workflows!
a(e) b(x) c(x) d(x) e(x) f(x) g(e) {
e.setField(...);
}
a(e) {
String s = b(vo);
e.setField(s);
}
b(โ€ฆ) c(โ€ฆ) d(โ€ฆ) e(โ€ฆ) f(โ€ฆ) g(โ€ฆ) {return ...;}
1) vavr.Tuple3<String,String,Integer>
2) NewConceptVO #kudos if you can find a good name!
can be pure functions
Immutable Arguments
Return the change to the surface, and apply it there
Return multiple changes:
220 ยฉ VictorRentea.ro
a training by
The Big Deal
Is when immutable objects travel lots of code
221 ยฉ VictorRentea.ro
a training by
Performance of Immutability
222 ยฉ VictorRentea.ro
a training by
Concerned of Performance?
Measure it !
(and you might have a surprise)
224 ยฉ VictorRentea.ro
a training by
Avoid Immutable Objects If
- Trashing millions of instances/second
- Cloning Lost of Collections
- Trivial logic (overkill)
- Persistent Entities or DTOs
225 ยฉ VictorRentea.ro
a training by
Take-Aways
โžข Complex logic โž” pure functions using immutable objects
โžข Functional Core / Imperative Shell
โžข Pull impure remote/DB calls in the shell
โžข We'll change it in there โž” compute and return
โžข Without proper mindset, immutability can hurt
โžข Don't mutate: argument state, variables or collections
โžข Immutable: runtime data or persistent leaves
โžข We'll change it in there โž” compute and return
And no, I'm against OOP; but not in huge logic code โž”
226 ยฉ VictorRentea.ro
a training by
victorrentea@gmail.com โ™ฆ โ™ฆ Training: VictorRentea.ro
โžขWe'll change it in there โž” compute and return

More Related Content

What's hot

Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Victor Rentea
ย 
้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......
้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......
้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......
hugo lu
ย 
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
ESUG
ย 

What's hot (20)

Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideEvolving a Clean, Pragmatic Architecture - A Craftsman's Guide
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
ย 
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
ย 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
ย 
Hibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the MagicHibernate and Spring - Unleash the Magic
Hibernate and Spring - Unleash the Magic
ย 
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
ย 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
ย 
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
ย 
้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......
้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......
้—œๆ–ผๆธฌ่ฉฆ๏ผŒๆˆ‘่ชช็š„ๅ…ถๅฏฆๆ˜ฏ......
ย 
Pharo Optimising JIT Internals
Pharo Optimising JIT InternalsPharo Optimising JIT Internals
Pharo Optimising JIT Internals
ย 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVM
ย 
TDD Training
TDD TrainingTDD Training
TDD Training
ย 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
ย 
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks Ad-hoc Runtime Object Structure Visualizations with MetaLinks
Ad-hoc Runtime Object Structure Visualizations with MetaLinks
ย 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015
ย 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017
ย 
Code lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf LinzCode lifecycle in the jvm - TopConf Linz
Code lifecycle in the jvm - TopConf Linz
ย 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
ย 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
ย 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
ย 
AOP in Python API design
AOP in Python API designAOP in Python API design
AOP in Python API design
ย 

Similar to Pure functions and immutable objects @dev nexus 2021

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
ย 
Java Generics
Java GenericsJava Generics
Java Generics
Carol McDonald
ย 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
ย 
NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#
NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#
NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#
tcaesvk
ย 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
ย 
Evolving The Java Language
Evolving The Java LanguageEvolving The Java Language
Evolving The Java Language
QConLondon2008
ย 

Similar to Pure functions and immutable objects @dev nexus 2021 (20)

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
ย 
Unit testing - 9 design hints
Unit testing - 9 design hintsUnit testing - 9 design hints
Unit testing - 9 design hints
ย 
Java Generics
Java GenericsJava Generics
Java Generics
ย 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
ย 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
ย 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
ย 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
ย 
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
ย 
The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5The why and how of moving to php 5.4/5.5
The why and how of moving to php 5.4/5.5
ย 
C++ theory
C++ theoryC++ theory
C++ theory
ย 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
ย 
NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#
NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#
NDC 2011, C++ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋ฅผ ์œ„ํ•œ C#
ย 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ย 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
ย 
Evolving The Java Language
Evolving The Java LanguageEvolving The Java Language
Evolving The Java Language
ย 
The craft of meta programming on JVM
The craft of meta programming on JVMThe craft of meta programming on JVM
The craft of meta programming on JVM
ย 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
ย 
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
ย 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
ย 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
ย 

More from 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
ย 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
Victor Rentea
ย 

More from 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
ย 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
ย 
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
ย 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
ย 
Profiling your Java Application
Profiling your Java ApplicationProfiling your Java Application
Profiling your Java Application
ย 
OAuth in the Wild
OAuth in the WildOAuth in the Wild
OAuth in the Wild
ย 
The tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptxThe tests are trying to tell you something@VoxxedBucharest.pptx
The tests are trying to tell you something@VoxxedBucharest.pptx
ย 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
ย 
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
ย 
Extreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software CraftsmanshipExtreme Professionalism - Software Craftsmanship
Extreme Professionalism - Software Craftsmanship
ย 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
ย 
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
ย 
TDD Mantra
TDD MantraTDD Mantra
TDD Mantra
ย 
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...
ย 

Recently uploaded

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
ย 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
ย 
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
ย 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
ย 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
sivaprakash250
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
SUHANI PANDEY
ย 

Recently uploaded (20)

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
ย 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
ย 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
ย 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
ย 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
ย 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
ย 
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
ย 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ย 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
ย 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
ย 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
ย 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
ย 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
ย 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
ย 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ย 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
ย 
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth โŸŸ 6297143586 โŸŸ Call Me For Genuine Se...
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
ย 

Pure functions and immutable objects @dev nexus 2021

  • 1. victor.rentea@gmail.com โ™ฆ โ™ฆ @victorrentea โ™ฆ VictorRentea.ro The Hitchhiker Guider to
  • 2. Victor Rentea Best Talks, Goodies, Blog: VictorRentea.ro Independent Trainer & Consultant Founder of Bucharest Software Craftsmanship Community Java Champion โค๏ธ Simple Design, Refactoring, Unit Testing โค๏ธ
  • 3. Technical Training Hibernate Spring Func Prog in Java 300+ days 2000 devs 8 years Training for you or your company: VictorRentea.ro 40 companies Follow me: 35K 4K 3K Java Performance Reactive-X Design Patterns Clean Code Refactoring Unit Testing TDD any lang
  • 4. 174 ยฉ VictorRentea.ro a training by Life
  • 5. 175 ยฉ VictorRentea.ro a training by checkCustomer(customer); checkOrder(customer, order); Mock-full tests Race Bugs A method changes a parameter: Surprise! Unexpected Different Results for Same Inputs customer.setActive(true); Temporal Coupling
  • 6. 176 ยฉ VictorRentea.ro a training by do side-effects return void sendEmail(Email):void Command-Query Separation setActive(true):void return results search(criteria):List computePrice(flight):int in 1994, by Bertrand Meyer Pure Functions
  • 7. 177 ยฉ VictorRentea.ro a training by No side effects No INSERTs, POSTs, queues, files, fields,โ€ฆ = ๐‘€๐‘Ž๐‘กโ„Ž๐‘’๐‘š๐‘Ž๐‘ก๐‘–๐‘๐‘Ž๐‘™ ๐น๐‘ข๐‘›๐‘๐‘ก๐‘–๐‘œ๐‘›๐‘ : ๐‘“ ๐‘ฅ, ๐‘ฆ = ๐‘ฅ2 + ๐‘ฆ (logging doesn't count) Referential Transparent Same Inputs โž” Same Output No current time, random, GET, SELECTโ€ฆ โ‰  Idempotent Pure Functions
  • 8. 178 ยฉ VictorRentea.ro a training by Referential Transparent Idempotent โ‰  f(1,2) = 3 f(1,2) can be replaced with 3 everywhere After calling f once Calling it again n times will not produce any extra changes Can Have Side Effects eg: DELETE FROM X WHERE ID = f(1,2) f(1,2) f(1,2)
  • 9. 179 ยฉ VictorRentea.ro a training by Pure Functions : Quiz f1(int x) {return x + 1;} f2(Data d) {return ++d.x;} f3() {d.incrementX(); return d.x;} f4() {return querySQL(...);} f5(int y) { return this.x + y; } f6(Data d, int y) { return d.getX() + y; } f7(int i) { if (i<0) throw new WrongInputException(); } is this immutable? Probable side effects Expected to be pure
  • 10. 180 ยฉ VictorRentea.ro a training by throw new E(); is pure f(x) { try { // } } catch (E) is pure? if it always throws for the same inputs it depends ... * Some slightly disagree on E NO, if E can happen randomly eg. IOException, OutOfMemory YES, if E is thrown deterministically* โž” Catch unexpected exceptions in the outskirts of your code
  • 11. 181 ยฉ VictorRentea.ro a training by Why we Love Pure Functions โžขNo hidden inputs, only plain-sight return values and parameters โžขEasier to understand โžขNo temporal coupling โžขTestable with less setup โžขFast & Composable: free to call them n times โž” โžขParallelizable (careful with instance functions on mutable objects) r=f(); a=g(r);
  • 12. 182 ยฉ VictorRentea.ro a training by Replace Temp Variable with Query If a function is pure + fast, it's safe to call it multiple times: Replace Parameter with Query var data = f(a,b); data data f(a,b) f(a,b) big(..., f(a,b)); param param void big(..., param) { f(a,b) f(a,b) they typically are
  • 13. 183 ยฉ VictorRentea.ro a training by you don't care how many times (and if) you call a pure function
  • 15. 185 ยฉ VictorRentea.ro a training by That's it! I'll make all my functions pure that's usually impossible What kind of app doesn't change anything?
  • 16. 186 ยฉ VictorRentea.ro a training by In Java there's no way to strictly enforce purity โž” We have to live with both pure and impure functions How do we distinguish them?
  • 17. 187 ยฉ VictorRentea.ro a training by do side-effects return void sendEmail(Email):void Command-Query Separation setActive(true):void return results pure functions search():List computePrice(movie):int Highlight Side Effects computePriceAndAdjustMetrics(movie):int
  • 18. 188 ยฉ VictorRentea.ro a training by You can do better!
  • 20. 190 ยฉ VictorRentea.ro a training by functional core Side-effects (Writes) + Non-deterministic Reads Expose them Purify the most complex parts of your logic!
  • 21. 191 ยฉ VictorRentea.ro a training by Purify the most complex parts of your logic!
  • 22. 193 ยฉ VictorRentea.ro a training by Purifying Logic Time and Random Amount of time-dependent logic: โžขNone (e.setCreationDate(now());) โž” tolerate โžขVery little โž” Inject a Clock / TimeProvider โžขHeavy (x-rare) โž” expose a ..., time); parameter
  • 23. 194 ยฉ VictorRentea.ro a training by No Files in Functional Core
  • 24. 196 ยฉ VictorRentea.ro a training by Initial Read Intermediary (conditional?) โž” Pass as Parameters โž” Split-Phase Refactor f(); r=read(); f(r); Writing Results โž” Return Changes w=f(); persist(w); r=read() Expose DB and HTTP calls imperative shell
  • 25. 197 ยฉ VictorRentea.ro a training by Expose DB and HTTP calls Initial Read Intermediary (conditional?) โž” Pass as Parameters โž” Split-Phase Refactor r=read(); f(r); r1=phase1(...) phase2(r,r1...) expose impurity Writing Results โž” Return Changes w=f(); persist(w); r=read() imperative shell Create new classes ๐Ÿ’ช
  • 26. 198 ยฉ VictorRentea.ro a training by Implement most complex logic as internal pure functions exposing impurity to the surface
  • 27. 199 ยฉ VictorRentea.ro a training by Pure Functions don't Change Objects' State Immutable Objects
  • 28. 200 ยฉ VictorRentea.ro a training by Immutable Objects
  • 29. 201 ยฉ VictorRentea.ro a training by void f(Data data) { ... if (data.getX() == 1) { // will this run ? } } void h() { Data data = new Data(1); obj.setData(data); g(data); } obj void g(Data data) { data.setX(2); mutateParam(data); obj.mutateField(); f(data); } void setData(Data data) { this.data = data; } void mutateField() { this.data.setX(2); } same obj in h() and g() void mutateParam(Data data) { data.setX(1); } x= Long-lived mutable data A Code Inspection Session What code ran before, having a reference to my data instance?! Mutable Data ... ...
  • 30. 202 ยฉ VictorRentea.ro a training by void f(Data data) { ... if (data.getX() == 1) { // will this run ? } } void h() { Data data = new Data(1); obj.setData(data); g(data); } obj void g(Data data) { data.setX(2); mutateParam(data); obj.mutateField(); f(data); } void setData(Data data) { this.data = data; } void mutateField() { this.data.setX(2); } same obj in h() and g() void mutateParam(Data data) { data.setX(1); } x= Long-lived mutable data A Code Inspection Session What code ran before, having a reference to my data instance?! Mutable Data Immutable Data ... ...
  • 31. 203 ยฉ VictorRentea.ro a training by void f(Data data) { ... if (data.getX() == 1) { // will this run ? } } void g(Data data) { f(data); } void h() { Data data = new Data(1); g(data); } A Code Inspection Session Immutable Data Who created the instance?! Easier to trace data changes x=
  • 32. 204 ยฉ VictorRentea.ro a training by Designing Immutable Classes public class A { private final String s; private final B b; private final List<String> list; public A(String s, B b, List<String> list) { this.s = s; this.b = b; this.list = new ArrayList<>(list); // validation ... } public List<String> getList() { return unmodifiableList(list); } // getters // hashCode, equals on all fields = Value Object // bits of LOGIC ๐Ÿ’ช public A withS(String newS) { return new A(newS, b, list); } } Mutates by creating a new instance Stops creator keeping a reference Overkill, as problem is not the creator but the "man-in-the-middle" Oh, so we CAN mutate them! @lombok.With Iterable<String> getList() { List<? extends String> getList() { or final fields, but not strictly required record (java 15) Java collections are mutable๐Ÿ˜ž final Afraid of hackers? ๐Ÿ˜จ @lombok.Value or, until then...
  • 33. 205 ยฉ VictorRentea.ro a training by Oh, so we CAN mutate them!
  • 34. 206 ยฉ VictorRentea.ro a training by A function changing an immutable object has to return it: data = updx(data); Imagine data has 20 fields ... every time data = updy(data); data = updz(data); The mess is still here! ๐ŸŽต Who changed the field X? How to fix?
  • 35. 207 ยฉ VictorRentea.ro a training by data = updx(data); data = updy(data); data = updz(data); final variables won't allow this IntelliJ underlines reassigned variables โค๏ธ By the way, there are ways to add final automatically at code cleanup Real Problem Too Large Immutable Objects data.xyz = createXYZ(...); โž” break them If they change together, they stick together = clutter; Extreme: Mark only the non-final with @Var (errorprone Java compiler from Google)
  • 36. 208 ยฉ VictorRentea.ro a training by Wait a second, I know...
  • 37. 209 ยฉ VictorRentea.ro a training by void f(VO[] arr) { arr[0] = arr[0].withX(-99); } void f(List<String> list) { list.removeIf(String::isBlank); } void f(Map<Integer, VO> map) { map.put(1, map.get(1).withX(-99)); } map.get(1).withX(-99)
  • 38. 210 ยฉ VictorRentea.ro a training by Don't ever mutate collections! โž” Create new ones
  • 39. 211 ยฉ VictorRentea.ro a training by Why we Immutable objects Easier to trace data changes Can enforce validation in constructor Safe to put in Set or Map(as keys) Thread-safe โž” no race bugs, since they can't be changed โž” their hashCode doesn't change
  • 40. 212 ยฉ VictorRentea.ro a training by All right cowboy! Only immutable objects from now on! usually that's too much!
  • 41. 214 ยฉ VictorRentea.ro a training by instead, Extract immutable Value Objects from their fields Leaving the root Entity mutable NO* *there are few cases when it pays to, but those apps typically don't persist their data Should Entities be immutable?
  • 42. 215 ยฉ VictorRentea.ro a training by @Entity (mutable) Persistent Immutable Leaf eg. FullName Immutable Objects in Real Life Non-Persistent Runtime Objects that you write heavy logic with continuously break Large Entities @Embeddable
  • 43. 216 ยฉ VictorRentea.ro a training by Non-Persistent Runtime Objects that you write heavy logic with Always Immutable
  • 44. 218 ยฉ VictorRentea.ro a training by The Big Deal
  • 45. 219 ยฉ VictorRentea.ro a training by The Big Deal Don't mutate objects on long workflows! a(e) b(x) c(x) d(x) e(x) f(x) g(e) { e.setField(...); } a(e) { String s = b(vo); e.setField(s); } b(โ€ฆ) c(โ€ฆ) d(โ€ฆ) e(โ€ฆ) f(โ€ฆ) g(โ€ฆ) {return ...;} 1) vavr.Tuple3<String,String,Integer> 2) NewConceptVO #kudos if you can find a good name! can be pure functions Immutable Arguments Return the change to the surface, and apply it there Return multiple changes:
  • 46. 220 ยฉ VictorRentea.ro a training by The Big Deal Is when immutable objects travel lots of code
  • 47. 221 ยฉ VictorRentea.ro a training by Performance of Immutability
  • 48. 222 ยฉ VictorRentea.ro a training by Concerned of Performance? Measure it ! (and you might have a surprise)
  • 49. 224 ยฉ VictorRentea.ro a training by Avoid Immutable Objects If - Trashing millions of instances/second - Cloning Lost of Collections - Trivial logic (overkill) - Persistent Entities or DTOs
  • 50. 225 ยฉ VictorRentea.ro a training by Take-Aways โžข Complex logic โž” pure functions using immutable objects โžข Functional Core / Imperative Shell โžข Pull impure remote/DB calls in the shell โžข We'll change it in there โž” compute and return โžข Without proper mindset, immutability can hurt โžข Don't mutate: argument state, variables or collections โžข Immutable: runtime data or persistent leaves โžข We'll change it in there โž” compute and return And no, I'm against OOP; but not in huge logic code โž”
  • 51. 226 ยฉ VictorRentea.ro a training by victorrentea@gmail.com โ™ฆ โ™ฆ Training: VictorRentea.ro โžขWe'll change it in there โž” compute and return