SlideShare a Scribd company logo
October 2012
Introduction to Refactoring




Noun: a change made to the internal structure of software to make it
easier to understand and cheaper to modify without changing its
observable behavior


Verb: to restructure software by applying a series of refactorings
without changing its observable behavior.
Good to know, Bruno




Now, show some code please.
Extract Method
Motivation

Extract Method is one of the most common refactorings. If a method that
is too long or look at code that needs a comment to understand its
purpose.

It does take a little getting used to if you are used to seeing larger
methods. And small methods really work only when you have good names,
so you need to pay attention to naming.

The key is the semantic distance between the method name and the
method body. If extracting improves clarity, do it, even if the name is
longer than the code you have extracted.
Extract Method
Code
void printOwing(double amount)
{
  printBanner();

    //print details
    System.out.println ("name:" + _name);
    System.out.println ("amount" + amount);
}
Extract Method
Code
void printOwing(double amount) {
 printBanner();

    //print details
    System.out.println ("name:" + _name);
    System.out.println ("amount" + amount);
}


void printOwing(double amount) {
  printBanner();
  printDetails(amount);
}

void printDetails (double amount) {
  System.out.println ("name:" + _name);
  System.out.println ("amount" + amount);
}
Introduce Explaining Variable
Motivation

Expressions can become very complex and hard to read. In such
situations variables can be helpful to break down the expression into
something more manageable.

Introduce Explaining Variable is particularly valuable with conditional
logic in which it is useful to take each clause of a condition and explain
what the condition means with a well-named.
Introduce Explaining Variable
Code
double price()
{
  // price is base price - quantity discount + shipping
  return _quantity * _itemPrice –
         Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
         Math.min(_quantity * _itemPrice * 0.1, 100.0);
}
Introduce Explaining Variable
Code
double price()
{
  // price is base price - quantity discount + shipping
  return _quantity * _itemPrice –
         Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
         Math.min(_quantity * _itemPrice * 0.1, 100.0);
}


double price()
{
  double basePrice = _quantity * _itemPrice;
  double quantityDiscount = Math.max(0, _quantity - 500) * _itemPrice *
0.05;
  double shipping = Math.min(basePrice * 0.1, 100.0);

    return basePrice - quantityDiscount + shipping;
}
Replace Temp with Query
Motivation

The problem with temps is that they are temporary and local. Because
they can be seen only in the context of the method in which they are used,
temps tend to encourage longer methods, because that’s the only way you
can reach the temp. By replacing the temp with a query method, any
method in the class can get at the information. That helps a lot in coming
up with cleaner code for the class.

The straightforward cases of this refactoring are those in which temps are
assigned only to once and those in which the expression that generates
the assignment is free of side effects. Other cases are trickier but
possible.
Replace Temp with Query
Code
double getPrice()
{
  int basePrice = _quantity * _itemPrice;
  double discountFactor;

    if (basePrice > 1000)
      discountFactor = 0.95;
    else
      discountFactor = 0.98;

    return basePrice * discountFactor;
}
Replace Temp with Query
Code
private int basePrice() {
  return _quantity * _itemPrice;
}

private double discountFactor() {
  if (basePrice() > 1000)
    return 0.95;
  else
    return 0.98;
}

double getPrice() {
  return basePrice() * discountFactor();
}
Substitute Algorithm
Motivation

I’ve never tried to skin a cat. I’m told there are several ways to do it. I’m
sure some are easier than others. So it is with algorithms. If you find a
clearer way to do something, you should replace the complicated way with
the clearer way. Refactoring can break down something complex into
simpler pieces, but sometimes you just reach the point at which you have
to remove the whole algorithm and replace it with something simpler. This
occurs as you learn more about the problem and realize that there’s an
easier way to do it. It also happens if you start using a library that supplies
features that duplicate your code.
Substitute Algorithm
Code
String foundPerson(String[] people){
  for (int i = 0; i < people.length; i++) {
    if (people[i].equals ("Don"))
      return "Don";
    if (people[i].equals ("John"))
      return "John";
    if (people[i].equals ("Kent"))
      return "Kent";
  }
  return "";
}
Substitute Algorithm
Code
String foundPerson(String[] people){
  for (int i = 0; i < people.length; i++) {
    if (people[i].equals ("Don"))
      return "Don";
    if (people[i].equals ("John"))
      return "John";
    if (people[i].equals ("Kent"))
      return "Kent";
  }
  return "";
}


String foundPerson(String[] people){
  List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"});
  for (int i=0; i<people.length; i++)
   if (candidates.contains(people[i]))
     return people[i];
  return "";
}
Extract Class
Motivation

You’ve probably heard that a class should be a crisp abstraction, handle a
few clear responsibilities, or some similar guideline. In practice, classes
grow. You add some operations here, a bit of data there. You add a
responsibility to a class feeling that it’s not worth a separate class, but as
that responsibility grows and breeds, the class becomes too complicated.
Soon your class is as crisp as a microwaved duck.
Extract Class
Code
public String getName() {
  return _name;
}
public String getTelephoneNumber() {
  return ("(" + _officeAreaCode + ") " + _officeNumber);
}
String getOfficeAreaCode() {
  return _officeAreaCode;
}
void setOfficeAreaCode(String arg) {
  _officeAreaCode = arg;
}
String getOfficeNumber() {
  return _officeNumber;
}
void setOfficeNumber(String arg) {
  _officeNumber = arg;
}
private String _name;
private String _officeAreaCode;
private String _officeNumber;
Extract Class
Code
private String _name;
private TelephoneNumber _officeTelephone = new TelephoneNumber();

public String getName() {
  return _name;
}
public String getTelephoneNumber(){
  return _officeTelephone.getTelephoneNumber();
}
TelephoneNumber getOfficeTelephone() {
  return _officeTelephone;
}
Extract Class
Code
private String _number;
private String _areaCode;

public String getTelephoneNumber() {
  return ("(" + _areaCode + ") " + _number);
}
String getAreaCode() {
  return _areaCode;
}
void setAreaCode(String arg) {
  _areaCode = arg;
}
String getNumber() {
  return _number;
}
void setNumber(String arg) {
  _number = arg;
}

More Related Content

PPTX
Pragmatic metaprogramming
PPT
Bad Smell in Codes - Part 1
PDF
Python overview
PPT
Oop lecture7
PDF
E2
PPTX
Chap1 array
PDF
Functions in python
PDF
Python dictionary : past, present, future
Pragmatic metaprogramming
Bad Smell in Codes - Part 1
Python overview
Oop lecture7
E2
Chap1 array
Functions in python
Python dictionary : past, present, future

What's hot (20)

PPTX
Basics of Python programming (part 2)
PPT
Chapter 2 Method in Java OOP
PPT
PPT
Chapter 4 - Classes in Java
PPT
Chapter 3 Arrays in Java
PPTX
PPTX
Chapter 14 strings
PDF
Python Functions (PyAtl Beginners Night)
PDF
Unbounded Error Communication Complexity of XOR Functions
PDF
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
PPTX
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
PPTX
Python Datatypes by SujithKumar
PDF
awesome groovy
PPTX
python chapter 1
PPTX
Python chapter 2
PPTX
Python Modules and Libraries
PDF
iRODS Rule Language Cheat Sheet
PDF
Python Modules, Packages and Libraries
Basics of Python programming (part 2)
Chapter 2 Method in Java OOP
Chapter 4 - Classes in Java
Chapter 3 Arrays in Java
Chapter 14 strings
Python Functions (PyAtl Beginners Night)
Unbounded Error Communication Complexity of XOR Functions
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
Python Datatypes by SujithKumar
awesome groovy
python chapter 1
Python chapter 2
Python Modules and Libraries
iRODS Rule Language Cheat Sheet
Python Modules, Packages and Libraries
Ad

Viewers also liked (19)

PDF
Ukrainian pavilion EXPO 2015
PPS
Vida Flores Permanentes - Franquias
PPTX
ShoeShop Franquias
PDF
union design competition 2012
PPT
Scada Café - Indicadores de Mercado
PPTX
Telaid: Technology Lifecycle Solutions
PPT
Kuzey Ormanları Savunması Sunumu
PDF
Ukrainian pavilion architecture EXPO 2015
PDF
iKing Franchising
PPTX
Estivanelli Franchising
PPT
Ppt software overview
PDF
Loja das Torcidas - Produtos e Valores
PPTX
INN530 - Assignment 2, Big data and cloud computing for management
PPT
GWArc 43rd Annual Harvest Breakfast Virtual Ad Book 2013
PPTX
Harvest Breakfast Visual Ad Presentation 2015
PPTX
Gençlere Umut Atölyesi
PPTX
Anime_FU_SaglamTapu_Tntm_Sunumu-Sunansiz
PDF
Presentation Zeezoo
Ukrainian pavilion EXPO 2015
Vida Flores Permanentes - Franquias
ShoeShop Franquias
union design competition 2012
Scada Café - Indicadores de Mercado
Telaid: Technology Lifecycle Solutions
Kuzey Ormanları Savunması Sunumu
Ukrainian pavilion architecture EXPO 2015
iKing Franchising
Estivanelli Franchising
Ppt software overview
Loja das Torcidas - Produtos e Valores
INN530 - Assignment 2, Big data and cloud computing for management
GWArc 43rd Annual Harvest Breakfast Virtual Ad Book 2013
Harvest Breakfast Visual Ad Presentation 2015
Gençlere Umut Atölyesi
Anime_FU_SaglamTapu_Tntm_Sunumu-Sunansiz
Presentation Zeezoo
Ad

Similar to Refactoring (20)

PPT
Composing method
PPTX
Introduction to Refactoring
PDF
Clean code
PDF
Martin Fowler's Refactoring Techniques Quick Reference
PDF
All you need to know about JavaScript Functions
PDF
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...
PPT
Practices For Becoming A Better Programmer
PDF
Refactoring 메소드 호출의 단순화
PPTX
Clean Code
PPT
Clean code _v2003
PPTX
Encapsulation
PPTX
A Details Overview How to Use Typescript Generic Type
PPT
Mixing functional and object oriented approaches to programming in C#
PPT
Mixing Functional and Object Oriented Approaches to Programming in C#
PPTX
20.1 Java working with abstraction
PPTX
Working effectively with legacy code
PDF
Clean code
PPT
Refactoring Tips by Martin Fowler
PPTX
Naming Standards, Clean Code
PDF
Addressing Scenario
Composing method
Introduction to Refactoring
Clean code
Martin Fowler's Refactoring Techniques Quick Reference
All you need to know about JavaScript Functions
Icsug dev day2014_road to damascus - conversion experience-lotusscript and @f...
Practices For Becoming A Better Programmer
Refactoring 메소드 호출의 단순화
Clean Code
Clean code _v2003
Encapsulation
A Details Overview How to Use Typescript Generic Type
Mixing functional and object oriented approaches to programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
20.1 Java working with abstraction
Working effectively with legacy code
Clean code
Refactoring Tips by Martin Fowler
Naming Standards, Clean Code
Addressing Scenario

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
KodekX | Application Modernization Development
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPT
Teaching material agriculture food technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
Cloud computing and distributed systems.
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Review of recent advances in non-invasive hemoglobin estimation
Understanding_Digital_Forensics_Presentation.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Electronic commerce courselecture one. Pdf
KodekX | Application Modernization Development
Encapsulation_ Review paper, used for researhc scholars
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Teaching material agriculture food technology
Digital-Transformation-Roadmap-for-Companies.pptx
cuic standard and advanced reporting.pdf
Cloud computing and distributed systems.
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Network Security Unit 5.pdf for BCA BBA.

Refactoring

  • 2. Introduction to Refactoring Noun: a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior Verb: to restructure software by applying a series of refactorings without changing its observable behavior.
  • 3. Good to know, Bruno Now, show some code please.
  • 4. Extract Method Motivation Extract Method is one of the most common refactorings. If a method that is too long or look at code that needs a comment to understand its purpose. It does take a little getting used to if you are used to seeing larger methods. And small methods really work only when you have good names, so you need to pay attention to naming. The key is the semantic distance between the method name and the method body. If extracting improves clarity, do it, even if the name is longer than the code you have extracted.
  • 5. Extract Method Code void printOwing(double amount) { printBanner(); //print details System.out.println ("name:" + _name); System.out.println ("amount" + amount); }
  • 6. Extract Method Code void printOwing(double amount) { printBanner(); //print details System.out.println ("name:" + _name); System.out.println ("amount" + amount); } void printOwing(double amount) { printBanner(); printDetails(amount); } void printDetails (double amount) { System.out.println ("name:" + _name); System.out.println ("amount" + amount); }
  • 7. Introduce Explaining Variable Motivation Expressions can become very complex and hard to read. In such situations variables can be helpful to break down the expression into something more manageable. Introduce Explaining Variable is particularly valuable with conditional logic in which it is useful to take each clause of a condition and explain what the condition means with a well-named.
  • 8. Introduce Explaining Variable Code double price() { // price is base price - quantity discount + shipping return _quantity * _itemPrice – Math.max(0, _quantity - 500) * _itemPrice * 0.05 + Math.min(_quantity * _itemPrice * 0.1, 100.0); }
  • 9. Introduce Explaining Variable Code double price() { // price is base price - quantity discount + shipping return _quantity * _itemPrice – Math.max(0, _quantity - 500) * _itemPrice * 0.05 + Math.min(_quantity * _itemPrice * 0.1, 100.0); } double price() { double basePrice = _quantity * _itemPrice; double quantityDiscount = Math.max(0, _quantity - 500) * _itemPrice * 0.05; double shipping = Math.min(basePrice * 0.1, 100.0); return basePrice - quantityDiscount + shipping; }
  • 10. Replace Temp with Query Motivation The problem with temps is that they are temporary and local. Because they can be seen only in the context of the method in which they are used, temps tend to encourage longer methods, because that’s the only way you can reach the temp. By replacing the temp with a query method, any method in the class can get at the information. That helps a lot in coming up with cleaner code for the class. The straightforward cases of this refactoring are those in which temps are assigned only to once and those in which the expression that generates the assignment is free of side effects. Other cases are trickier but possible.
  • 11. Replace Temp with Query Code double getPrice() { int basePrice = _quantity * _itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; }
  • 12. Replace Temp with Query Code private int basePrice() { return _quantity * _itemPrice; } private double discountFactor() { if (basePrice() > 1000) return 0.95; else return 0.98; } double getPrice() { return basePrice() * discountFactor(); }
  • 13. Substitute Algorithm Motivation I’ve never tried to skin a cat. I’m told there are several ways to do it. I’m sure some are easier than others. So it is with algorithms. If you find a clearer way to do something, you should replace the complicated way with the clearer way. Refactoring can break down something complex into simpler pieces, but sometimes you just reach the point at which you have to remove the whole algorithm and replace it with something simpler. This occurs as you learn more about the problem and realize that there’s an easier way to do it. It also happens if you start using a library that supplies features that duplicate your code.
  • 14. Substitute Algorithm Code String foundPerson(String[] people){ for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")) return "Don"; if (people[i].equals ("John")) return "John"; if (people[i].equals ("Kent")) return "Kent"; } return ""; }
  • 15. Substitute Algorithm Code String foundPerson(String[] people){ for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")) return "Don"; if (people[i].equals ("John")) return "John"; if (people[i].equals ("Kent")) return "Kent"; } return ""; } String foundPerson(String[] people){ List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"}); for (int i=0; i<people.length; i++) if (candidates.contains(people[i])) return people[i]; return ""; }
  • 16. Extract Class Motivation You’ve probably heard that a class should be a crisp abstraction, handle a few clear responsibilities, or some similar guideline. In practice, classes grow. You add some operations here, a bit of data there. You add a responsibility to a class feeling that it’s not worth a separate class, but as that responsibility grows and breeds, the class becomes too complicated. Soon your class is as crisp as a microwaved duck.
  • 17. Extract Class Code public String getName() { return _name; } public String getTelephoneNumber() { return ("(" + _officeAreaCode + ") " + _officeNumber); } String getOfficeAreaCode() { return _officeAreaCode; } void setOfficeAreaCode(String arg) { _officeAreaCode = arg; } String getOfficeNumber() { return _officeNumber; } void setOfficeNumber(String arg) { _officeNumber = arg; } private String _name; private String _officeAreaCode; private String _officeNumber;
  • 18. Extract Class Code private String _name; private TelephoneNumber _officeTelephone = new TelephoneNumber(); public String getName() { return _name; } public String getTelephoneNumber(){ return _officeTelephone.getTelephoneNumber(); } TelephoneNumber getOfficeTelephone() { return _officeTelephone; }
  • 19. Extract Class Code private String _number; private String _areaCode; public String getTelephoneNumber() { return ("(" + _areaCode + ") " + _number); } String getAreaCode() { return _areaCode; } void setAreaCode(String arg) { _areaCode = arg; } String getNumber() { return _number; } void setNumber(String arg) { _number = arg; }