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
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладкаDEVTYPE
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
conditional statements
conditional statementsconditional statements
conditional statementsJames Brotsos
 
From typing the test to testing the type
From typing the test to testing the typeFrom typing the test to testing the type
From typing the test to testing the typeWim Godden
 
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
 

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
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
conditional statements
conditional statementsconditional statements
conditional statements
 
From typing the test to testing the type
From typing the test to testing the typeFrom typing the test to testing the type
From typing the test to testing the type
 
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
 

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

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 Ontologyjohnbeverley2021
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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
 
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 SavingEdi Saputra
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
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
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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
 
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
 
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
 
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
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
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, Adobeapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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
 

Recently uploaded (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
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
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 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...
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
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...
 
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
 
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
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 

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