SlideShare a Scribd company logo
Refactoring
Sempre, senza pietà!
BrewBox
29 gennaio 2018
Scaletta
1. Smells
2. Riscrittura vs refactoring
3. Codice, codice, codice
Roberto
Albertini
r.albertini@newgenesys.it
@robalbertini
www.linkedin.com/in/robertoalbertini
www.newgenesys.it
La presentazione contains
un uso discontinuo
of italiano and english
Attenzione
Fonti
Clean Code: A Handbook of Agile
Software Craftsmanship
Robert C. Martin (2008)
Extreme Programming Explained:
Embrace Change
Kent Beck (1999)
Refactoring: Improving
the Design of Existing Code
Martin Fowler (1999)
@milanoxpug
@milanoxpug
“
”
Any fool can write code
that a computer can understand.
Good programmers write
code that humans can understand
Refactoring: Improving the Design of Existing Code: Martin Fowler
“
”
Programming is the art of
telling another human being
what one wants the computer to do
Donald Knuth
Codice come comunicazione
Cosa comunica
Dominio
Design
Intenzioni
Come comunica
Attendibile
Verificabile
Contesti e stili
contesti diversi generano stili diversi
Linguaggi
Tecnologie
Framework
Community
Competenze
Personalità
Mi ispiro a OOP
Ma molti concetti sono applicabili a qualunque contesto
Attenzione
“
”
Problems with projects
can invariably be traced back to
somebody not talking to somebody else
about something important
Kent Beck, Extreme Programming Explained: Embrace Change
La comunicazione può essere problematica
Faticoso da leggere
10 a 1
Nasconde bachi
Comportamenti non evidenti aiutano a nascondersi
Difficile da modificare
Comprensione del design e delle intenzioni
Invita al degrado
Finestra rotta
“
”
is a surface indication
that usually corresponds to
a deeper problem in the system
Code smell
Duplicated code
Liar Names
Uncommunicative Name
Inconsistent Names
Comments
Mixing levels of abstraction
within a function
Data Clumps
Primitive Obsession
Long Method
Long Names
Long Parameter List
Large Class
Code Smells (catalogo completo?)
Feature Envy
Inappropriate Intimacy
Incomplete Library Class
Middle Man
Message Chains
Alternative Classes with
Different Interfaces
Refused Bequest
Switch Statements
Temporary Field
Divergent Change
Shotgun Surgery
Parallel Inheritance
Hierarchies
Dead Code
Data Class
Lazy Class
Speculative Generality
Incomplete Library Class
Message Chains
Middle Man
Conditional Complexity
Combinatorial Explosion
Type Embedded in Name
Oddball Solution
Indecent Exposure
Solution Sprawl
Excessive use of literals
Cyclomatic complexity
Downcasting
Orphan variable or constant
class
Excessively short identifiers
Excessively long identifiers
Excessive return of data
Code Smells: Duplicated code
“Number one in the stink parade”
(Martin Fowler - Refactoring
“Root of all evil”
(Robert C. Martin - Clean Code)
“The bane of software development”
(Jeff Atwood - blog.codinghorror.com)
Code Smells: smells nei nomi
Liar names
Metodi con effetti collaterali, diversi da quel che ci si aspetta
Uncommunicative names
Descrivono efficacemente? Lasciano intendere quello che accadrà?
Inconsistent names
Terminologia, convenzioni.
Code Smells: Comments
public void printReport(Date now) {
printBanner();
// print details
System.out.println("name: " + name);
System.out.println("amount: " + getOutstanding());
// footer
int sdf = new SimpleDateFormat("dd MMM yyyy");
System.out.println("======================");
System.out.println(sdf.format(now));
System.out.println("======================");
}
Code Smells: Duplicated code
“Root of all evil”
(Robert C. Martin - Clean Code)
Code Smells: Mixing levels of abstraction within a function
public void printReport(User user, BigDecimal rate, Date now) {
printHeader(user);
printUserDetails(user);
BigDecimal points = getTotalPoints();
BigDecimal coins = points.divide(rate, 0, FLOOR);
BigDecimal gold = coins.divide(CHANGE, 0, FLOOR);
BigDecimal silver = coins.subtract(gold.multiply(CHANGE));
System.out.println(" ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~");
System.out.println("Points: " + points + " ");
System.out.println(" Value: " + gold + "gold " + silver + "silver");
System.out.println(" ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~");
printFooter(now);
}
Code Smells: Data Clumps
“Data items tend to be like children;
they enjoy hanging around in groups together”
void drawPoint(int xPos, int yPos);
double valueBetween(Date startDate, Date endDate);
void drawPoint(Point point);
double valueBetween(DateInterval interval);
Code Smells: Primitive Obsession
double computeValue(List<Invoice> invoices){ … }
List<Invoice> readAllInvoicesOfMonth(Date mese){ … }
List<Invoice> readAllInvoicesOfMonth(int anno, int mese){ … }
Packages findByTrackingCode(String bfTrackingCode){ … }
“Use small objects for small tasks”
Code Smells: Feature Envy
“a method that seems more interested
in a class other than the one it actually is in.”
public class Amount {
public void computeTotal(Item item) {
int amount1 = item.getAmountOne();
int amount2 = item.getAmountTwo();
int amount3 = item.getAmountThree();
int total = amount1 + amount2 + amount3;
item.setTotal(total);
}
Code Smells: Duplicated code
Duplicated code
Root of all evil
Uno alla volta
gli smells si accumulano
Demo!
Il codice peggiora nel tempo
Soluzione 1: Riscrittura
Organizzare la riscrittura
Tempo, Risorse e Organizzazione
Ma il valore è poco visibile
Sviluppo interrotto o parallelo?
Risorse suddivise o nuove?
Rilascio big bang o incrementale?
Quale valore si ottiene?
Cosa si riscrive?
Bisogna riportare TUTTE le features
Nascoste, dimenticate, bug
La verità sta solo nel codice
non nella memoria o nella documentazione
Sicuro che sapresti
fare meglio?
Ma soprattutto…
La riscrittura è la soluzione giusta
‣ Per adeguamento tecnologico
‣ Quando l’accesso al sorgente è difficile
‣ Per accedere a nuove tecnologie
‣ …
Non per fare le pulizie
Soluzione 2: Refactoring
Sempre, senza pietà!
“
”
Programmers restructure the system
without changing its behavior
to remove duplication,
improve communication,
simplify, or add flexibility
Refactoring
Kent Beck da “Extreme Programming Explained”
“
”
Refactoring is a disciplined technique
for restructuring an existing body of code,
altering its internal structure
without changing its external behavior
Refactoring
Martin Fowler dalla home page di www.refactoring.com
1. Miglioramento del codice
2. Nessuna aggiunta o modifica
di funzionalità
3. Tecnica disciplinata
Refactoring
‣ Dopo aver aggiunto una feature: per pulire
‣ Prima di aggiungere una feature: per fare spazio
‣ Per consolidare un livello di comprensione del
problema
“as I gain understanding about the program, I embed that understanding
into the code for later so I don't forget what I learned”
‣ Per comprendere codice ignoto che si sta
esplorando
‣ Per stanare un baco
‣ Ogni volta che puzza
Quando? Sempre!
Come? Senza pietà!
‣ Coraggio
‣ Costanza e disciplina
‣ Nessuna tolleranza per i difetti
1. Two hats
2. Baby steps
3. Test automatici
4. Undo
In pratica: 4 punti fondamentali
In pratica: (1) Two hats
Make it work
Aggiungi le features
Punti a una soluzione semplice che funzioni
Make it clean
Non modifichi il comportamento del sistema
Approfitti della conoscenza acquisita
In pratica: (2) Baby steps
Modifiche semplici
La probabilità di sbagliare è bassa
Sistema rimane sempre funzionante
Ogni modifica non rompe il sistema
In pratica: (3) Test automatici
Evitare le regressioni
Rete di sicurezza
Evitare la paura
La confidenza è fondamentale
per affrontare le ristrutturazioni più audaci
In pratica (4) Undo
Deve essere facile ricominciare
commit, refactor, commit, refactor, REVERT
Quando ricominciare?
Quando sei insicuro a metà di un refactoring
Quando sei fuori controllo
Come si ricomincia
Con passi più piccoli e idee più chiare
Passi di refactoring: catalogo completo (?)
Add Parameter
Change Bidirectional
Association to Unidirectional
Change Reference to Value
Change Unidirectional
Association to Bidirectional
Change Value to Reference
Collapse Hierarchy
Consolidate Conditional
Expression
Consolidate Duplicate
Conditional Fragments
Decompose Conditional
Duplicate Observed Data
Dynamic Method Definition
Eagerly Initialized Attribute
Encapsulate Collection
Encapsulate Downcast
Encapsulate Field
Extract Class
Extract Interface
Extract Method
Extract Module
Extract Subclass
Extract Superclass
Extract Surrounding Method
Extract Variable
Form Template Method
Hide Delegate
Hide Method
Inline Class
Inline Method
Inline Module
Inline Temp
Introduce Assertion
Introduce Class Annotation
Introduce Expression Builder
Introduce Foreign Method
Introduce Gateway
Introduce Local Extension
Introduce Named Parameter
Introduce Null Object
Introduce Parameter Object
Isolate Dynamic Receptor
Lazily Initialized Attribute
Move Eval from Runtime to
Parse Time
Move Field
Move Method
Parameterize Method
Preserve Whole Object
Pull Up Constructor Body
Pull Up Field
Pull Up Method
Push Down Field
Push Down Method
Recompose Conditional
Remove Assignments to
Parameters
Remove Control Flag
Remove Middle Man
Remove Named Parameter
Remove Parameter
Remove Setting Method
Remove Unused Default
Parameter
Rename Method
Replace Abstract Superclass
with Module
Replace Array with Object
Replace Conditional with
Polymorphism
Replace Constructor with
Factory Method
Replace Data Value with
Object
Replace Delegation With
Hierarchy
Replace Delegation with
Inheritance
Replace Dynamic Receptor
with Dynamic Method
Definition
Replace Error Code with
Exception
Replace Exception with Test
Replace Hash with Object
Replace Inheritance with
Delegation
Replace Loop with Collection
Closure Method
Replace Magic Number with
Symbolic Constant
Replace Method with Method
Object
Replace Nested Conditional
with Guard Clauses
Replace Parameter with
Explicit Methods
Replace Parameter with
Method
Replace Record with Data
Class
Replace Subclass with Fields
Replace Temp with Chain
Replace Temp with Query
Replace Type Code with Class
Replace Type Code with
Module Extension
Replace Type Code With
Polymorphism
Replace Type Code with
State/Strategy
Replace Type Code with
Subclasses
Self Encapsulate Field
Separate Query from Modifier
Split Temporary Variable
Substitute Algorithm
Replace Nested Conditional with Guard Clauses
double getPayAmount() {
double result;
if (isDead){
result = deadAmount();
} else {
if (isSeparated) {
result = separatedAmount();
} else {
if (isRetired) {
result = retiredAmount();
} else {
result = normalPayAmount();
}
}
}
return result;
}
double getPayAmount() {
if (isDead) {
return deadAmount();
}
if (isSeparated) {
return separatedAmount();
}
if (isRetired) {
return retiredAmount();
}
return normalPayAmount();
}
Prima Dopo
Introduce Parameter Object (prima)
public int getValBetween(Date startDate, Date endDate) {
int result = 0;
for (Entry each : entries) {
if ((each.getDate().after(startDate)
&& each.getDate().before(endDate))
|| each.getDate().equals(startDate)
|| each.getDate().equals(endDate)) {
result += each.getValue();
}
}
return result;
}
Introduce Parameter Object (dopo)
public int getValBetween(DateInterval dateInterval) {
int result = 0;
for (Entry each : entries) {
if (dateInterval.include(each.getDate())) {
result += each.getValue();
}
}
return result;
}
Introduce Parameter Object (dopo)
public class DateInterval {
private final Date startDate;
private final Date endDate;
public DateInterval(Date startDate, Date endDate) {
this.startDate = startDate;
this.endDate = endDate;
}
public boolean include(Date date) {
if ((date.after(startDate) && date.before(endDate))) {
return true;
}
if (date.equals(startDate) || date.equals(endDate)) {
return true;
}
return false;
}
}
Da dove si comincia? In quale direzione? Chi guida?
Principi di design
Clean code, GRASP, SOLID
Soluzioni a problemi comuni
Design pattern
Provare più soluzioni possibili
Spike, refactor/revert
“
”
Talk is cheap.
Show me the code
Linus Torvalds
Domande?
Grazie per
l’attenzione
Fine
Roberto Albertini
r.albertini@newgenesys.it
@robalbertini
www.linkedin.com/in/robertoalbertini
www.newgenesys.it
Credits
‣ Presentation template: Gremio by Slidescarnival
http://www.slidescarnival.com/gremio-free-presentation-template/1593
‣ Base color: Marsala #964F4C by Pantone
http://www.pantone.com/color-of-the-year-2015
https://www.pantone.com/color-finder/18-1438-TCX
‣ Font: Roboto by Google (Christian Robertson)
https://fonts.google.com/specimen/Roboto
‣ Font: Great Vibes by TypeSETit
https://fonts.google.com/specimen/Great+Vibes
‣ Icons: Font Awesome Vector Icons/Glyphs
https://goo.gl/vdQGpu, http://fontawesome.io/

More Related Content

Similar to 2018 01-29 - brewbox - refactoring. sempre, senza pietà

Refactoring 2 The Max
Refactoring 2 The MaxRefactoring 2 The Max
Refactoring 2 The Max
Alfredo Morresi
 
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard WorkTaming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Joseph Yoder
 
From Duke of DevOps to Queen of Chaos - Api days 2018
From Duke of DevOps to Queen of Chaos - Api days 2018From Duke of DevOps to Queen of Chaos - Api days 2018
From Duke of DevOps to Queen of Chaos - Api days 2018
Christophe Rochefolle
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
jexp
 
Codemotion Berlin 2015 recap
Codemotion Berlin 2015   recapCodemotion Berlin 2015   recap
Codemotion Berlin 2015 recap
Torben Dohrn
 
Patterns for organic architecture codedive
Patterns for organic architecture codedivePatterns for organic architecture codedive
Patterns for organic architecture codedive
magda3695
 
Practices of agile developers
Practices of agile developersPractices of agile developers
Practices of agile developers
DUONG Trong Tan
 
Refactoring, Emergent Design & Evolutionary Architecture
Refactoring, Emergent Design & Evolutionary ArchitectureRefactoring, Emergent Design & Evolutionary Architecture
Refactoring, Emergent Design & Evolutionary Architecture
Brad Appleton
 
refactoring code by clean code rules
refactoring code by clean code rulesrefactoring code by clean code rules
refactoring code by clean code rules
saber tabatabaee
 
The "Evils" of Optimization
The "Evils" of OptimizationThe "Evils" of Optimization
The "Evils" of OptimizationBlackRabbitCoder
 
Refactoring
RefactoringRefactoring
Refactoring
Behrouz Bakhtiari
 
agile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdfagile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdf
shreyassoni7
 
Software craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your teamSoftware craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your team
Dattatray Kale
 
One Engine Two Tools
One Engine Two ToolsOne Engine Two Tools
One Engine Two Tools
Chris Eargle
 
Periodic Table of Agile Principles and Practices
Periodic Table of Agile Principles and PracticesPeriodic Table of Agile Principles and Practices
Periodic Table of Agile Principles and Practices
Jérôme Kehrli
 
Techfest design patterns
Techfest design patternsTechfest design patterns
Techfest design patterns
RookieOne
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)guestebde
 
Of Changes and Their History
Of Changes and Their HistoryOf Changes and Their History
Of Changes and Their History
University of Zurich
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
Antonio de la Torre Fernández
 

Similar to 2018 01-29 - brewbox - refactoring. sempre, senza pietà (20)

Refactoring 2 The Max
Refactoring 2 The MaxRefactoring 2 The Max
Refactoring 2 The Max
 
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard WorkTaming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
Taming Big Balls of Mud with Diligence, Agile Practices, and Hard Work
 
From Duke of DevOps to Queen of Chaos - Api days 2018
From Duke of DevOps to Queen of Chaos - Api days 2018From Duke of DevOps to Queen of Chaos - Api days 2018
From Duke of DevOps to Queen of Chaos - Api days 2018
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
 
Codemotion Berlin 2015 recap
Codemotion Berlin 2015   recapCodemotion Berlin 2015   recap
Codemotion Berlin 2015 recap
 
Patterns for organic architecture codedive
Patterns for organic architecture codedivePatterns for organic architecture codedive
Patterns for organic architecture codedive
 
Practices of agile developers
Practices of agile developersPractices of agile developers
Practices of agile developers
 
Refactoring, Emergent Design & Evolutionary Architecture
Refactoring, Emergent Design & Evolutionary ArchitectureRefactoring, Emergent Design & Evolutionary Architecture
Refactoring, Emergent Design & Evolutionary Architecture
 
refactoring code by clean code rules
refactoring code by clean code rulesrefactoring code by clean code rules
refactoring code by clean code rules
 
The "Evils" of Optimization
The "Evils" of OptimizationThe "Evils" of Optimization
The "Evils" of Optimization
 
Refactoring
RefactoringRefactoring
Refactoring
 
agile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdfagile refactoring and integration techniques.pdf
agile refactoring and integration techniques.pdf
 
Software craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your teamSoftware craftsmanship and you a strong foundation in your team
Software craftsmanship and you a strong foundation in your team
 
One Engine Two Tools
One Engine Two ToolsOne Engine Two Tools
One Engine Two Tools
 
Periodic Table of Agile Principles and Practices
Periodic Table of Agile Principles and PracticesPeriodic Table of Agile Principles and Practices
Periodic Table of Agile Principles and Practices
 
Techfest design patterns
Techfest design patternsTechfest design patterns
Techfest design patterns
 
10 Ways To Improve Your Code( Neal Ford)
10  Ways To  Improve  Your  Code( Neal  Ford)10  Ways To  Improve  Your  Code( Neal  Ford)
10 Ways To Improve Your Code( Neal Ford)
 
Of Changes and Their History
Of Changes and Their HistoryOf Changes and Their History
Of Changes and Their History
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
 
Tech talks#6: Code Refactoring
Tech talks#6: Code RefactoringTech talks#6: Code Refactoring
Tech talks#6: Code Refactoring
 

Recently uploaded

Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 

Recently uploaded (20)

Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 

2018 01-29 - brewbox - refactoring. sempre, senza pietà

  • 1.
  • 2. Refactoring Sempre, senza pietà! BrewBox 29 gennaio 2018 Scaletta 1. Smells 2. Riscrittura vs refactoring 3. Codice, codice, codice
  • 4. La presentazione contains un uso discontinuo of italiano and english Attenzione
  • 5. Fonti Clean Code: A Handbook of Agile Software Craftsmanship Robert C. Martin (2008) Extreme Programming Explained: Embrace Change Kent Beck (1999) Refactoring: Improving the Design of Existing Code Martin Fowler (1999) @milanoxpug @milanoxpug
  • 6. “ ” Any fool can write code that a computer can understand. Good programmers write code that humans can understand Refactoring: Improving the Design of Existing Code: Martin Fowler
  • 7. “ ” Programming is the art of telling another human being what one wants the computer to do Donald Knuth
  • 8. Codice come comunicazione Cosa comunica Dominio Design Intenzioni Come comunica Attendibile Verificabile
  • 9. Contesti e stili contesti diversi generano stili diversi Linguaggi Tecnologie Framework Community Competenze Personalità
  • 10. Mi ispiro a OOP Ma molti concetti sono applicabili a qualunque contesto Attenzione
  • 11. “ ” Problems with projects can invariably be traced back to somebody not talking to somebody else about something important Kent Beck, Extreme Programming Explained: Embrace Change
  • 12. La comunicazione può essere problematica Faticoso da leggere 10 a 1 Nasconde bachi Comportamenti non evidenti aiutano a nascondersi Difficile da modificare Comprensione del design e delle intenzioni Invita al degrado Finestra rotta
  • 13. “ ” is a surface indication that usually corresponds to a deeper problem in the system Code smell
  • 14. Duplicated code Liar Names Uncommunicative Name Inconsistent Names Comments Mixing levels of abstraction within a function Data Clumps Primitive Obsession Long Method Long Names Long Parameter List Large Class Code Smells (catalogo completo?) Feature Envy Inappropriate Intimacy Incomplete Library Class Middle Man Message Chains Alternative Classes with Different Interfaces Refused Bequest Switch Statements Temporary Field Divergent Change Shotgun Surgery Parallel Inheritance Hierarchies Dead Code Data Class Lazy Class Speculative Generality Incomplete Library Class Message Chains Middle Man Conditional Complexity Combinatorial Explosion Type Embedded in Name Oddball Solution Indecent Exposure Solution Sprawl Excessive use of literals Cyclomatic complexity Downcasting Orphan variable or constant class Excessively short identifiers Excessively long identifiers Excessive return of data
  • 15. Code Smells: Duplicated code “Number one in the stink parade” (Martin Fowler - Refactoring “Root of all evil” (Robert C. Martin - Clean Code) “The bane of software development” (Jeff Atwood - blog.codinghorror.com)
  • 16. Code Smells: smells nei nomi Liar names Metodi con effetti collaterali, diversi da quel che ci si aspetta Uncommunicative names Descrivono efficacemente? Lasciano intendere quello che accadrà? Inconsistent names Terminologia, convenzioni.
  • 17. Code Smells: Comments public void printReport(Date now) { printBanner(); // print details System.out.println("name: " + name); System.out.println("amount: " + getOutstanding()); // footer int sdf = new SimpleDateFormat("dd MMM yyyy"); System.out.println("======================"); System.out.println(sdf.format(now)); System.out.println("======================"); }
  • 18. Code Smells: Duplicated code “Root of all evil” (Robert C. Martin - Clean Code)
  • 19. Code Smells: Mixing levels of abstraction within a function public void printReport(User user, BigDecimal rate, Date now) { printHeader(user); printUserDetails(user); BigDecimal points = getTotalPoints(); BigDecimal coins = points.divide(rate, 0, FLOOR); BigDecimal gold = coins.divide(CHANGE, 0, FLOOR); BigDecimal silver = coins.subtract(gold.multiply(CHANGE)); System.out.println(" ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~"); System.out.println("Points: " + points + " "); System.out.println(" Value: " + gold + "gold " + silver + "silver"); System.out.println(" ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~"); printFooter(now); }
  • 20. Code Smells: Data Clumps “Data items tend to be like children; they enjoy hanging around in groups together” void drawPoint(int xPos, int yPos); double valueBetween(Date startDate, Date endDate); void drawPoint(Point point); double valueBetween(DateInterval interval);
  • 21. Code Smells: Primitive Obsession double computeValue(List<Invoice> invoices){ … } List<Invoice> readAllInvoicesOfMonth(Date mese){ … } List<Invoice> readAllInvoicesOfMonth(int anno, int mese){ … } Packages findByTrackingCode(String bfTrackingCode){ … } “Use small objects for small tasks”
  • 22. Code Smells: Feature Envy “a method that seems more interested in a class other than the one it actually is in.” public class Amount { public void computeTotal(Item item) { int amount1 = item.getAmountOne(); int amount2 = item.getAmountTwo(); int amount3 = item.getAmountThree(); int total = amount1 + amount2 + amount3; item.setTotal(total); }
  • 23. Code Smells: Duplicated code Duplicated code Root of all evil
  • 24. Uno alla volta gli smells si accumulano Demo!
  • 25. Il codice peggiora nel tempo
  • 27. Organizzare la riscrittura Tempo, Risorse e Organizzazione Ma il valore è poco visibile Sviluppo interrotto o parallelo? Risorse suddivise o nuove? Rilascio big bang o incrementale? Quale valore si ottiene?
  • 28. Cosa si riscrive? Bisogna riportare TUTTE le features Nascoste, dimenticate, bug La verità sta solo nel codice non nella memoria o nella documentazione
  • 29. Sicuro che sapresti fare meglio? Ma soprattutto…
  • 30.
  • 31. La riscrittura è la soluzione giusta ‣ Per adeguamento tecnologico ‣ Quando l’accesso al sorgente è difficile ‣ Per accedere a nuove tecnologie ‣ … Non per fare le pulizie
  • 33. “ ” Programmers restructure the system without changing its behavior to remove duplication, improve communication, simplify, or add flexibility Refactoring Kent Beck da “Extreme Programming Explained”
  • 34. “ ” Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior Refactoring Martin Fowler dalla home page di www.refactoring.com
  • 35. 1. Miglioramento del codice 2. Nessuna aggiunta o modifica di funzionalità 3. Tecnica disciplinata Refactoring
  • 36. ‣ Dopo aver aggiunto una feature: per pulire ‣ Prima di aggiungere una feature: per fare spazio ‣ Per consolidare un livello di comprensione del problema “as I gain understanding about the program, I embed that understanding into the code for later so I don't forget what I learned” ‣ Per comprendere codice ignoto che si sta esplorando ‣ Per stanare un baco ‣ Ogni volta che puzza Quando? Sempre!
  • 37. Come? Senza pietà! ‣ Coraggio ‣ Costanza e disciplina ‣ Nessuna tolleranza per i difetti
  • 38. 1. Two hats 2. Baby steps 3. Test automatici 4. Undo In pratica: 4 punti fondamentali
  • 39. In pratica: (1) Two hats Make it work Aggiungi le features Punti a una soluzione semplice che funzioni Make it clean Non modifichi il comportamento del sistema Approfitti della conoscenza acquisita
  • 40. In pratica: (2) Baby steps Modifiche semplici La probabilità di sbagliare è bassa Sistema rimane sempre funzionante Ogni modifica non rompe il sistema
  • 41. In pratica: (3) Test automatici Evitare le regressioni Rete di sicurezza Evitare la paura La confidenza è fondamentale per affrontare le ristrutturazioni più audaci
  • 42. In pratica (4) Undo Deve essere facile ricominciare commit, refactor, commit, refactor, REVERT Quando ricominciare? Quando sei insicuro a metà di un refactoring Quando sei fuori controllo Come si ricomincia Con passi più piccoli e idee più chiare
  • 43. Passi di refactoring: catalogo completo (?) Add Parameter Change Bidirectional Association to Unidirectional Change Reference to Value Change Unidirectional Association to Bidirectional Change Value to Reference Collapse Hierarchy Consolidate Conditional Expression Consolidate Duplicate Conditional Fragments Decompose Conditional Duplicate Observed Data Dynamic Method Definition Eagerly Initialized Attribute Encapsulate Collection Encapsulate Downcast Encapsulate Field Extract Class Extract Interface Extract Method Extract Module Extract Subclass Extract Superclass Extract Surrounding Method Extract Variable Form Template Method Hide Delegate Hide Method Inline Class Inline Method Inline Module Inline Temp Introduce Assertion Introduce Class Annotation Introduce Expression Builder Introduce Foreign Method Introduce Gateway Introduce Local Extension Introduce Named Parameter Introduce Null Object Introduce Parameter Object Isolate Dynamic Receptor Lazily Initialized Attribute Move Eval from Runtime to Parse Time Move Field Move Method Parameterize Method Preserve Whole Object Pull Up Constructor Body Pull Up Field Pull Up Method Push Down Field Push Down Method Recompose Conditional Remove Assignments to Parameters Remove Control Flag Remove Middle Man Remove Named Parameter Remove Parameter Remove Setting Method Remove Unused Default Parameter Rename Method Replace Abstract Superclass with Module Replace Array with Object Replace Conditional with Polymorphism Replace Constructor with Factory Method Replace Data Value with Object Replace Delegation With Hierarchy Replace Delegation with Inheritance Replace Dynamic Receptor with Dynamic Method Definition Replace Error Code with Exception Replace Exception with Test Replace Hash with Object Replace Inheritance with Delegation Replace Loop with Collection Closure Method Replace Magic Number with Symbolic Constant Replace Method with Method Object Replace Nested Conditional with Guard Clauses Replace Parameter with Explicit Methods Replace Parameter with Method Replace Record with Data Class Replace Subclass with Fields Replace Temp with Chain Replace Temp with Query Replace Type Code with Class Replace Type Code with Module Extension Replace Type Code With Polymorphism Replace Type Code with State/Strategy Replace Type Code with Subclasses Self Encapsulate Field Separate Query from Modifier Split Temporary Variable Substitute Algorithm
  • 44. Replace Nested Conditional with Guard Clauses double getPayAmount() { double result; if (isDead){ result = deadAmount(); } else { if (isSeparated) { result = separatedAmount(); } else { if (isRetired) { result = retiredAmount(); } else { result = normalPayAmount(); } } } return result; } double getPayAmount() { if (isDead) { return deadAmount(); } if (isSeparated) { return separatedAmount(); } if (isRetired) { return retiredAmount(); } return normalPayAmount(); } Prima Dopo
  • 45. Introduce Parameter Object (prima) public int getValBetween(Date startDate, Date endDate) { int result = 0; for (Entry each : entries) { if ((each.getDate().after(startDate) && each.getDate().before(endDate)) || each.getDate().equals(startDate) || each.getDate().equals(endDate)) { result += each.getValue(); } } return result; }
  • 46. Introduce Parameter Object (dopo) public int getValBetween(DateInterval dateInterval) { int result = 0; for (Entry each : entries) { if (dateInterval.include(each.getDate())) { result += each.getValue(); } } return result; }
  • 47. Introduce Parameter Object (dopo) public class DateInterval { private final Date startDate; private final Date endDate; public DateInterval(Date startDate, Date endDate) { this.startDate = startDate; this.endDate = endDate; } public boolean include(Date date) { if ((date.after(startDate) && date.before(endDate))) { return true; } if (date.equals(startDate) || date.equals(endDate)) { return true; } return false; } }
  • 48. Da dove si comincia? In quale direzione? Chi guida? Principi di design Clean code, GRASP, SOLID Soluzioni a problemi comuni Design pattern Provare più soluzioni possibili Spike, refactor/revert
  • 49. “ ” Talk is cheap. Show me the code Linus Torvalds
  • 52. Credits ‣ Presentation template: Gremio by Slidescarnival http://www.slidescarnival.com/gremio-free-presentation-template/1593 ‣ Base color: Marsala #964F4C by Pantone http://www.pantone.com/color-of-the-year-2015 https://www.pantone.com/color-finder/18-1438-TCX ‣ Font: Roboto by Google (Christian Robertson) https://fonts.google.com/specimen/Roboto ‣ Font: Great Vibes by TypeSETit https://fonts.google.com/specimen/Great+Vibes ‣ Icons: Font Awesome Vector Icons/Glyphs https://goo.gl/vdQGpu, http://fontawesome.io/