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

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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.pdfsudhanshuwaghmare1
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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