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
 
Beautiful java script
Beautiful java scriptBeautiful java script
Beautiful java scriptÜrgo Ringo
 
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
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
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
 
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 deriveSanderSlideShare
 
Pro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsPro Java Fx – Developing Enterprise Applications
Pro Java Fx – Developing Enterprise ApplicationsStephen Chin
 

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

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

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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...DianaGray10
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
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 ...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
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...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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...Jeffrey Haguewood
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
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, ...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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)Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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 ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

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