In our quest against increasing complexity, Extract Method is probably the most important refactoring technique in our hands. We use it a dozen times per day as a first-level weapon, and very often it leads to us to deeper design insights. Let’s look at several such further actions you might take after pulling some code out in a separate method:
* Reorder Parameters
* Remove parameters by including more lines in what you extract (Ctrl-Z)
* Add parameters for reuse by extract/inline variable at call site (Ctrl-Z)
* Move method to object (for Feature Envy)
* Encapsulate conditionals (great with Java8)
* Inline back
* Distill switch expressions: the 3 Clean Switch Rules
* Introduce Method Object for heavy logic
* Early return errors
* Extract static util functions
* Spawn smart Value Object vs logic in Utils
* Extract’n-test then mock away, leading to Separation by Layers of Abstraction
* Command-Query Separation: mind the side effects
* Extract again - boolean vs SRP
* Wrap call to safely add more code (Open-Closed)
5. ➢ Largest 4 Java Meetups in Bucharest
Yearly, in Q2, at Bucharest Java User Group
➢ Meetups everywhere I travel to teach
Monthly 3-hours sessions, afterhours, throughout Europe: victorrentea.ro/#meetup
➢
Join for free: victorrentea.ro/community
13. VictorRentea.ro
A Clean Switch:
is the only instruction in a method
default: throw new
One-line per case
: return func();
: func(); break;
return switch
JEP 325: Switch Expressions
In Java 13… soon…
14. VictorRentea.ro
if (αααααα && βββββββ || γγγγγγγγ || ! δδδδδδδ)
Encapsulate Conditionals
if (α(..) && β(..) || γ(..) || ! δ(..))
if (αβ(..) || γδ(..))
19. VictorRentea.ro
How to refactor God Methods
of 500 lines ?
Extract Method Object refactor
138
Hint
A class should have less
than 200-300 lines
You make it a class
20. VictorRentea.ro
No side effects
Prefer returning over changing
Pure Functions
139
Same result for same inputs
no externals, time or Random
convertUser(user):UserDto
24. VictorRentea.ro
1. Rename
2. Inline
3. Reorder Params
4. Remove Params by extracting more (with Ctrl-Z)
5. Distill switch expressions to Clean Switch Rules
6. Early return errors
7. Add parameters for reuse by extract/inline variable at call site (Ctrl-Z)
8. Move method to object (vs Feature Envy)
9. Encapsulate conditionals
10. Extract static Util functions
11. Spawn Value Objects to host extracted logic
12. Extract again - boolean vs SRP
13. Wrap call to “safely” add more code (Open-Closed Principle)
14. Extract Method Object for heavy logic
15. Extract Pure Functions
25. I'm available
a statement of seniority
I use both hemispheres
Tough meetings?
Abused estimates?
Purpose of code:--Uncle Bob
1. Maintainable
2. Does its job!
Functional Party
Activist
Stay into
The Light
Trainings, talks, goodies, Good stuff daily on:
Clean Code
needs strength
and determination
Thank You!
+
Join my community
Code: https://github.com/victorrentea/refactoring