Docsity

Refactoring - Lecture Notes - Advanced Object-Oriented Programming | CS 3331, Study notes of Computer Science

Toggle sidebar
bg1
1/14/2009
1
Refactoring
(from Martin Fowler, Refactoring:
Improving the Design of Existing Code,
Addison Wesley, 1999.
Refactoring
• “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.”
Why
•Usually, good design first, then code
second.
Refactoring is the reverse process
•Take bad design
•Rework it into a good design
Example
•Program calculates and prints a statement of a
customer’s charges to a video store.
•We know what movies and how long the
customer had them.
•There are three kinds of movies: regular,
children’s, and new releases.
• Program computes a renter’s frequent renter
points, which vary depending on whether the
film is a new release.
// From book: 'Refactoring' by Martin Fowler
public class Movie {
public static final int CHILDRENS = 2;
public static final int NEW_RELEASE = 1;
public static final int REGULAR = 0;
private String _title;
private int _priceCode;
public Movie(String title, int priceCode) {
_title = title;
_priceCode = priceCode;
}
public int getPriceCode() {
return _priceCode;
}
public void setPriceCode(int arg) {
_priceCode = arg;
}
public String getTitle() {
return _title;
}
}
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Refactoring - Lecture Notes - Advanced Object-Oriented Programming | CS 3331 and more Study notes Computer Science in PDF only on Docsity!

Refactoring

(from Martin Fowler, Refactoring:

Improving the Design of Existing Code ,

Addison Wesley, 1999.

Refactoring

• “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.”

Why

• Usually, good design first, then code

second.

Refactoring is the reverse process

• Take bad design

• Rework it into a good design

Example

• Program calculates and prints a statement of a

customer’s charges to a video store.

• We know what movies and how long the

customer had them.

• There are three kinds of movies: regular,

children’s, and new releases.

• Program computes a renter’s frequent renter

points, which vary depending on whether the

film is a new release.

// From book: 'Refactoring' by Martin Fowler public class Movie { public static final int CHILDRENS = 2; public static final int NEW_RELEASE = 1; public static final int REGULAR = 0; private String _title; private int _priceCode; public Movie(String title, int priceCode) { _title = title; _priceCode = priceCode; } public int getPriceCode() { }^ return _priceCode; public void setPriceCode(int arg) { _priceCode = arg; } public String getTitle() { return _title; }^ }

public class Rental { private Movie _movie; private int _daysRented; public Rental(Movie movie, int daysRented) { _movie = movie; _daysRented = daysRented; } public int getDaysRented() { return _daysRented; } public Movie getMovie() { return _movie; } }

import java.util.Enumeration;

import java.util.Vector;

public class Customer {

private String _name;

private Vector _rentals = new Vector();

public Customer(String name) {

_name = name;

public void addRental(Rental arg) {

_rentals.addElement(arg);

public String getName() {

return _name;

public String statement() { double totalAmount = 0; int frequentRenterPoints = 0; Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + getName() + "\n"; while (rentals.hasMoreElements()) { double thisAmount = 0; Rental each = (Rental) rentals.nextElement(); //determine amounts for each line switch (each.getMovie().getPriceCode()) { case Movie.REGULAR: case Movie.NEW_RELEASE: }^ case Movie.CHILDRENS: // add frequent renter points frequentRenterPoints++; // add bonus for a two day new release rental if ((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) && each.getDaysRented() > 1) frequentRenterPoints++; // show figures for this rental result += "\t" + each.getMovie().getTitle() + "\t" + String.valueOf(thisAmount) + "\n"; }^ totalAmount += thisAmount; // add footer lines result += "Amount owed is " + String.valueOf(totalAmount) + "\n"; result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent renter points"; }^ return result; More code here …

Draw UML Class diagram of this

Draw UML Sequence diagram of

statement()

Impressions of the code?

Junit

public class CustomerTest extends TestCase { public void testStatementForManyMovies() { Customer customer1 = new Customer("David"); Movie movie1 = new Movie("Madagascar", Movie.CHILDRENS); Rental rental1 = new Rental(movie1, 6); // 6 day rental Movie movie2 = new Movie("Star Wars", Movie.NEW_RELEASE); Rental rental2 = new Rental(movie2, 2); // 2 day rental Movie movie3 = new Movie("Gone with the Wind", Movie.REGULAR); Rental rental3 = new Rental(movie3, 8); // 8 day rental customer1.addRental(rental1); customer1.addRental(rental2); customer1.addRental(rental3); String expected = "Rental Record for David\n" + +^ "\tMadagascar\t6.0\n" + "\tStar Wars\t6.0\n" +"\tGone with the Wind\t11.0\n" "Amount owed is 23.0\n" + "You earned 4 frequent renter points"; String statement = customer1.statement(); assertEquals(expected, statement); }

First target: statement()

• Why?

Approach

• Extract cohesive methods that can be

reused

Extract Method

• You have a code fragment that can be grouped

together.

• Turn the fragment into a method with a name

explaining the purpose.

• Mechanics:

  • Create a new method
  • Copy extracted code from source to target
  • Find variables local to source method but not local to extracted code. Make them parameters to new method.
  • Check for local variables modified in extracted code. (If there is more than one, you may need to refactor before extracting the method.)
  • Replace extracted code with a call to the target method.
  • Compile and test. public String statement() { double totalAmount = 0; int frequentRenterPoints = 0; Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + getName() + "\n"; while (rentals.hasMoreElements()) { double thisAmount = 0; Rental each = (Rental) rentals.nextElement(); thisAmount = amountFor(each); // add frequent renter points frequentRenterPoints++; // add bonus for a two day new release rental if ((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) && each.getDaysRented() > 1) frequentRenterPoints++; // show figures for this rental result += "\t" + each.getMovie().getTitle() + "\t" + String.valueOf(thisAmount) + "\n"; }^ totalAmount += thisAmount; // add footer lines result += "Amount owed is " + String.valueOf(totalAmount) + "\n"; result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent renter points"; }^ return result; New Method .. private int amountFor (Rental each) { int thisAmount = 0; switch (each.getMovie().getPriceCode()) { case Movie.REGULAR: thisAmount += 2; if (each.getDaysRented() > 2) thisAmount += (each.getDaysRented() - 2) * 1.5; break; case Movie.NEW_RELEASE: thisAmount += each.getDaysRented() * 3; break; case Movie.CHILDRENS: thisAmount += 1.5; if (each.getDaysRented() > 3) thisAmount += (each.getDaysRented() - 3) * 1.5; break; } return thisAmount; }

Advice:

• Refactor in small steps and test.

• If you make a mistake, it’s easier to find

Next step: amountFor

• Some of the names aren’t very descriptive

• Rename Variable

private double amountFor (Rental each) {

int thisAmount = 0;

switch (each.getMovie().getPriceCode()) {

case Movie.REGULAR:

thisAmount += 2;

if (each.getDaysRented() > 2)

thisAmount += (each.getDaysRented() - 2) * 1.5;

break;

case Movie.NEW_RELEASE:

thisAmount += each.getDaysRented() * 3;

break;

case Movie.CHILDRENS:

thisAmount += 1.5;

if (each.getDaysRented() > 3)

thisAmount += (each.getDaysRented() - 3) * 1.5;

break;

return thisAmount;

private double amountFor (Rental aRental) {

int result = 0;

switch (aRental.getMovie().getPriceCode()) {

case Movie.REGULAR:

result += 2;

if (aRental.getDaysRented() > 2)

result += (aRental.getDaysRented() - 2) * 1.5;

break;

case Movie.NEW_RELEASE:

result += aRental.getDaysRented() * 3;

break;

case Movie.CHILDRENS:

result += 1.5;

if (aRental.getDaysRented() > 3)

result += (aRental.getDaysRented() - 3) * 1.5;

break;

return result;

Run the tests

>java - cp "..\junit.jar;..;." CustomerTest

Time: 0.

OK (7 tests)

Advice

Any fool can write code a computer can

understand. Good programmers write

code that humans can understand.

public String htmlStatement() {

Enumeration rentals = _rentals.elements();

String result = "Rentals for " + getName() + "\n";

while (rentals.hasMoreElements()) {

Rental each = (Rental) rentals.nextElement();

// show figures for this rental

result += each.getMovie().getTitle() + ": " +

String.valueOf(each.getCharge()) + "\n";

// add footer lines

result += "

You Owe " + String.valueOf(getTotalCharge()) +

"

\n";

result += "On this rental you earned " +

String.valueOf(getTotalFrequentRenterPoints()) + " frequent renter

points

";

return result;

Redraw the UML diagrams

Draw UML Sequence diagram of

statement()

aCustomer aRental aMovie statement() *[for all rentals] getCharge getPriceCode getTotalCharge getTotalFrequentRenterPoints *[for all rentals] getFrequentRenterPoints getPriceCode

Not done yet: The conditional logic

is suspect

• The switch statement in Rental is

controlled by attributes of Movie

• This is usually not a good idea

• Keep control with the data, so

– Move getCharge() to Movie

But what varies with the rental

type?

Change

• Recall that the clients are going to change

the types of rentals.

## • Move frequent renter computation to

Rental

• Compute the charge and the frequent

renter points in Movie (passing in the

number of days from Rental)

• Things that vary with the type are together

in the same class

Situation

• There are several types of movies

• For each type of movie, we have different

ways to compute charges and frequent

rental points

• We expect to be changing the types of

movies

Replace Conditional Logic with

Polymorphism

• You have a conditional that chooses

different behavior depending on the type

of an object

• Move each leg of the conditional to an

overriding method in a subclass. Make the

original method abstract

How?

How do we fix this? To introduce State

• Replace Type Code with State

• Move Method (move switch to Price class)

• Replace conditional with Polymorphism (to

eliminate the switch)

UML Class Diagram

Price getCharge getFrequentRenterPoints(days:int) New Release Price getCharge getFrequentRenterPoints Children’s Price getCharge Regular Price getCharge Movie getCharge (days: int) getFrequentRenterPoints(days:int) Title: String Rental getCharge() getFrequentRenterPoints() daysRented: int Customer Statement() getTotalCharge() getTotalFrequentRenterPoints()

  • name: String

Draw UML Sequence diagram of

statement()

aCustomer aRental aMovie statement() *[for all rentals] getCharge (^) getCharge(days) getTotalCharge getTotalFrequentRenterPoints *[for all rentals] getFrequentRenterPoints getFrequentRenterPoints(days) aPrice getCharge(days) getFrequentRenter(days)

What’s the last thing to do? Status

• What happens if we add new movie

types? How do we change the code to

support this?

• What happens if we add pricing based on

a customer’s frequent renter points?

Refactoring

• Continuous process

– Refactor, test, refactor, test, …

• Do when you need to maintain code

– Refactor to a clean design

– Implement change