SlideShare a Scribd company logo
1 of 16
Download to read offline
Refactoring di codice
        legacy

Fabiana Romagnoli
Tommaso Torti
Refactoring: definizione

“Refactoring is the process of changing a software
system in such a way that it does not alter the external
behavior of the code yet improves its internal
structure.”

Martin Fowler
I principi del refactoring:

• Migliorare il design del codice
• Eliminare le duplicazioni (ridurre la quantità di
  codice)

• Rendere il codice più leggibile e facile da modificare
package com.sourcesense.refactoring.workshop;

import java.util.Iterator;
import java.util.List;

public class CaloriesCalculator {
   private List<Food> foods;
   private final Person person;

   public CaloriesCalculator(Person person, List<Food> foods) {
      this.person = person;
      this.foods = foods;
   }
   public String result() throws Exception {
      String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
      double cal = 0.0;
      for (int i = 0; i < foods.size(); i++) {
         Food food = foods.get(i);
         string += food.name + quot; - quot; + food.kg + quot;nquot;;
         if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
         if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
         if (quot;magicPillquot;.equals(food.name)) cal -= 10;
         if (quot;candyquot;.equals(food.name)) cal += food.kg;
      }
      string += quot;Total: quot; + cal + quot; kcalnquot;;
      string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ *
person.size() / cal;
      for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
         Food type = (Food) iterator.next();
         if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
         if (person.getKg() > 1000) throw new SecondException();
      }
      return string;
   }
}
Le regole:

• Tempo a disposizione: 20 minuti
• I test devono restare verdi
• I test non possono essere modificati.
  (Ad esempio non puoi modificare i parametri di
  input e output, mentre puoi creare nuovi oggetti
  usati “internamente”
Magic numbers

  public String result() throws Exception {
     String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
     double cal = 0.0;
     for (int i = 0; i < foods.size(); i++) {
        Food food = foods.get(i);
        string += food.name + quot; - quot; + food.kg + quot;nquot;;
        if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
        if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
        if (quot;magicPillquot;.equals(food.name)) cal -= 10;
        if (quot;candyquot;.equals(food.name)) cal += food.kg;
     }
     string += quot;Total: quot; + cal + quot; kcalnquot;;
      string += quot;kilometers to be run: quot; + 90 /* calories in one           kilometer */
* person.size() / cal;
      for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
         Food type = (Food) iterator.next();
         if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
         if (person.getKg() > 1000) throw new SecondException();
      }
      return string;
   }
}
Uso delle costanti parziale
   public Person(String name, int kg) {
      this.name = name;
      this.kg = kg;
   }

   public String getName() {
      return name;
   }

   public int getKg() {
      return kg;
   }
   }
   public int size() {
       if (kg > 130)
         return 3;
       if (kg < 50)
         return 1;
       return MEDIUM_SIZE;
   }
Nomi di variabili metodi e classi
   public String result() throws Exception {
      String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
      double cal = 0.0;
      for (int i = 0; i < foods.size(); i++) {
         Food food = foods.get(i);
         string += food.name + quot; - quot; + food.kg + quot;nquot;;
         if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
         if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
         if (quot;magicPillquot;.equals(food.name)) cal -= 10;
         if (quot;candyquot;.equals(food.name)) cal += food.kg;
      }
      string += quot;Total: quot; + cal + quot; kcalnquot;;
      string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer
*/ * person.size() / cal;
      for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
         Food type = (Food) iterator.next();
         if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
         if (person.getKg() > 1000) throw new SecondException();
      }
      return string;
   }
}
Cicli for
    public String result() throws Exception {
       String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
       double cal = 0.0;
        for (int i = 0; i < foods.size(); i++) {
          Food food = foods.get(i);
          string += food.name + quot; - quot; + food.kg + quot;nquot;;
          if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
          if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
          if (quot;magicPillquot;.equals(food.name)) cal -= 10;
          if (quot;candyquot;.equals(food.name)) cal += food.kg;
     }
     string += quot;Total: quot; + cal + quot; kcalnquot;;
     string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ *
person.size() / cal;
        for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
          Food type = (Food) iterator.next();
          if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
          if (person.getKg() > 1000) throw new SecondException();
        }
        return string;
    }
}
Responsabilità
                               1. Costruzione del report
...
      public String result() throws Exception {
          String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
          double cal = 0.0;
          for (int i = 0; i < foods.size(); i++) {
             Food food = foods.get(i);
              string += food.name + quot; - quot; + food.kg + quot;nquot;;
              if   (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
              if   (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
              if   (quot;magicPillquot;.equals(food.name)) cal -= 10;
              if   (quot;candyquot;.equals(food.name)) cal += food.kg;
          }
    string += quot;Total: quot; + cal + quot; kcalnquot;;
    string += quot;kilometers to be run: quot; + 90 /* calories in one
kilometer */ * person.size() / cal;
          for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
             Food type = (Food) iterator.next();
             if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
             if (person.getKg() > 1000) throw new SecondException();
          }
          return string;
      }
}
Responsabilità
                                2. Calcolo delle calorie
...
      public String result() throws Exception {
         String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
         double cal = 0.0;
         for (int i = 0; i < foods.size(); i++) {
            Food food = foods.get(i);
            string += food.name + quot; - quot; + food.kg + quot;nquot;;
             if   (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
             if   (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
             if   (quot;magicPillquot;.equals(food.name)) cal -= 10;
             if   (quot;candyquot;.equals(food.name)) cal += food.kg;
          }
          string += quot;Total: quot; + cal + quot; kcalnquot;;
          string += quot;kilometers to be run: quot; + 90   /* calories in one kilometer */ *
person.size() / cal;
          for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
             Food type = (Food) iterator.next();
             if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
             if (person.getKg() > 1000) throw new SecondException();
          }
          return string;
      }
}
Responsabilità
                                        3.Validazione
...
      public String result() throws Exception {
         String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
         double cal = 0.0;
         for (int i = 0; i < foods.size(); i++) {
            Food food = foods.get(i);
            string += food.name + quot; - quot; + food.kg + quot;nquot;;
             if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
             if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
             if (quot;magicPillquot;.equals(food.name)) cal -= 10;
             if (quot;candyquot;.equals(food.name)) cal += food.kg;
          }
          string += quot;Total: quot; + cal + quot; kcalnquot;;
          string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() /
cal;
          for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
             Food type = (Food) iterator.next();
             if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
             if (person.getKg() > 1000) throw new SecondException();
          }
          return string;
      }
}
Validazione: posizione e ripetizione
    public String result() throws Exception {
       String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
       double cal = 0.0;
       for (int i = 0; i < foods.size(); i++) {
          Food food = foods.get(i);
          string += food.name + quot; - quot; + food.kg + quot;nquot;;
            if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException();
            if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
            if (quot;magicPillquot;.equals(food.name)) cal -= 10;
            if (quot;candyquot;.equals(food.name)) cal += food.kg;
     }
     string += quot;Total: quot; + cal + quot; kcalnquot;;
     string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ *
person.size() / cal;
     for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
        Food type = (Food) iterator.next();
            if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
            if (person.getKg() > 1000) throw new SecondException();
        }
        return string;
    }
}
Accesso ai field privati
  public String result() throws Exception {
     String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;;
     double cal = 0.0;
     for (int i = 0; i < foods.size(); i++) {
        Food food = foods.get(i);
        string += food.name + quot; - quot; + food.kg + quot;nquot;;
        if (quot;quot;.equalsIgnoreCase(food.name)) throw new
FirstException();
        if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10;
       if (quot;magicPillquot;.equals(food.name)) cal -= 10;
       if (quot;candyquot;.equals(food.name)) cal +=     food.kg;
     }
     string += quot;Total: quot; + cal + quot; kcalnquot;;
     string += quot;kilometers to be run: quot; + 90 /* calories in one
kilometer */ * person.size() / cal;
     for (Iterator iterator = foods.iterator(); iterator.hasNext();) {
        Food type = (Food) iterator.next();
        if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException();
        if (person.getKg() > 1000) throw new SecondException();
     }
     return string;
   }
}
Riferimenti:

• Refactoring: Improving the Design
  of Existing Code - Martin Fowler




• Refactoring To Patterns - Joshua
  Kerievsky
Riferimenti:
• Refactoring Workbook - William
  Wake




• Working Effectively With Legacy
  Code - Michael Feathers

More Related Content

Similar to Workshop Sul Refactoring Agile Day 2008

I am trying to cover the protected synchronized boolean enoughIngred.pdf
I am trying to cover the protected synchronized boolean enoughIngred.pdfI am trying to cover the protected synchronized boolean enoughIngred.pdf
I am trying to cover the protected synchronized boolean enoughIngred.pdfallystraders
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfcalderoncasto9163
 
Design patterns in the 21st Century
Design patterns in the 21st CenturyDesign patterns in the 21st Century
Design patterns in the 21st CenturySamir Talwar
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Basel Issmail
 
Hello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdfHello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdffedosys
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладкаDEVTYPE
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
conditional statements
conditional statementsconditional statements
conditional statementsJames Brotsos
 
From typing the test to testing the type
From typing the test to testing the typeFrom typing the test to testing the type
From typing the test to testing the typeWim Godden
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean testsDanylenko Max
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfNicholasflqStewartl
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Waytdc-globalcode
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
TDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypeTDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypetdc-globalcode
 

Similar to Workshop Sul Refactoring Agile Day 2008 (20)

I am trying to cover the protected synchronized boolean enoughIngred.pdf
I am trying to cover the protected synchronized boolean enoughIngred.pdfI am trying to cover the protected synchronized boolean enoughIngred.pdf
I am trying to cover the protected synchronized boolean enoughIngred.pdf
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
 
Design patterns in the 21st Century
Design patterns in the 21st CenturyDesign patterns in the 21st Century
Design patterns in the 21st Century
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.Symfony (Unit, Functional) Testing.
Symfony (Unit, Functional) Testing.
 
Hello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdfHello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdf
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
conditional statements
conditional statementsconditional statements
conditional statements
 
From typing the test to testing the type
From typing the test to testing the typeFrom typing the test to testing the type
From typing the test to testing the type
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
TDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypeTDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hype
 

More from Tommaso Torti

Lavorare in un team agile
Lavorare in un team agileLavorare in un team agile
Lavorare in un team agileTommaso Torti
 
Antica presentazione AJAX
Antica presentazione AJAXAntica presentazione AJAX
Antica presentazione AJAXTommaso Torti
 
Presentazione noestimates
Presentazione noestimatesPresentazione noestimates
Presentazione noestimatesTommaso Torti
 
JProfiler / an introduction
JProfiler / an introductionJProfiler / an introduction
JProfiler / an introductionTommaso Torti
 
Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...
Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...
Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...Tommaso Torti
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacyTommaso Torti
 

More from Tommaso Torti (6)

Lavorare in un team agile
Lavorare in un team agileLavorare in un team agile
Lavorare in un team agile
 
Antica presentazione AJAX
Antica presentazione AJAXAntica presentazione AJAX
Antica presentazione AJAX
 
Presentazione noestimates
Presentazione noestimatesPresentazione noestimates
Presentazione noestimates
 
JProfiler / an introduction
JProfiler / an introductionJProfiler / an introduction
JProfiler / an introduction
 
Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...
Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...
Agile Day 2012 - Sviluppo agile in un contesto bancario: come far convivere t...
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacy
 

Recently uploaded

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Recently uploaded (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Workshop Sul Refactoring Agile Day 2008

  • 1. Refactoring di codice legacy Fabiana Romagnoli Tommaso Torti
  • 2. Refactoring: definizione “Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure.” Martin Fowler
  • 3. I principi del refactoring: • Migliorare il design del codice • Eliminare le duplicazioni (ridurre la quantità di codice) • Rendere il codice più leggibile e facile da modificare
  • 4. package com.sourcesense.refactoring.workshop; import java.util.Iterator; import java.util.List; public class CaloriesCalculator { private List<Food> foods; private final Person person; public CaloriesCalculator(Person person, List<Food> foods) { this.person = person; this.foods = foods; } public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 5. Le regole: • Tempo a disposizione: 20 minuti • I test devono restare verdi • I test non possono essere modificati. (Ad esempio non puoi modificare i parametri di input e output, mentre puoi creare nuovi oggetti usati “internamente”
  • 6. Magic numbers public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 7. Uso delle costanti parziale public Person(String name, int kg) { this.name = name; this.kg = kg; } public String getName() { return name; } public int getKg() { return kg; } } public int size() { if (kg > 130) return 3; if (kg < 50) return 1; return MEDIUM_SIZE; }
  • 8. Nomi di variabili metodi e classi public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 9. Cicli for public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 10. Responsabilità 1. Costruzione del report ... public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 11. Responsabilità 2. Calcolo delle calorie ... public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 12. Responsabilità 3.Validazione ... public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 13. Validazione: posizione e ripetizione public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 14. Accesso ai field privati public String result() throws Exception { String string = quot;Diet Report for quot; + person.getName() +quot;:nquot;; double cal = 0.0; for (int i = 0; i < foods.size(); i++) { Food food = foods.get(i); string += food.name + quot; - quot; + food.kg + quot;nquot;; if (quot;quot;.equalsIgnoreCase(food.name)) throw new FirstException(); if (quot;applequot;.equals(food.name)) cal += food.kg * 15 * 10; if (quot;magicPillquot;.equals(food.name)) cal -= 10; if (quot;candyquot;.equals(food.name)) cal += food.kg; } string += quot;Total: quot; + cal + quot; kcalnquot;; string += quot;kilometers to be run: quot; + 90 /* calories in one kilometer */ * person.size() / cal; for (Iterator iterator = foods.iterator(); iterator.hasNext();) { Food type = (Food) iterator.next(); if (quot;quot;.equalsIgnoreCase(type.name)) throw new FirstException(); if (person.getKg() > 1000) throw new SecondException(); } return string; } }
  • 15. Riferimenti: • Refactoring: Improving the Design of Existing Code - Martin Fowler • Refactoring To Patterns - Joshua Kerievsky
  • 16. Riferimenti: • Refactoring Workbook - William Wake • Working Effectively With Legacy Code - Michael Feathers