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.pdf
allystraders
 
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
calderoncasto9163
 
Design patterns in the 21st Century
Design patterns in the 21st CenturyDesign patterns in the 21st Century
Design patterns in the 21st Century
Samir Talwar
 
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
fedosys
 
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
NicholasflqStewartl
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 

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
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java script
 
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
 
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
 
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
 
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
 
ALE2014 let tests drive or let dijkstra derive
ALE2014 let tests drive or let dijkstra deriveALE2014 let tests drive or let dijkstra derive
ALE2014 let tests drive or let dijkstra derive
 
Pro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsPro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise Applications
 

More from Tommaso 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

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
 

Recently uploaded (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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