Docsity

Refactoring Tutorial: Part 2 - Improving Code Design with Martin Fowler's Techniques, Study notes of Computer Science

Toggle sidebar
bg1
Lecture 28: Refactoring (part 2)
Kenneth M. Anderson
Object-Oriented Analysis and Design
CSCI 6448 - Spring Semester, 2003
April 17, 2003 © University of Colorado, 2003 2
Credit where Credit is Due
Some of the material for this lecture and
lecture 25 is taken from “Refactoring:
Improving the Design of Existing Code”
by Martin Fowler; as such some
material is copyright © Addison Wesley,
1999
April 17, 2003 © University of Colorado, 2003 3
Last Lecture
Refactoring
Introduced core ideas
Improve design without changing functionality
Watch out for “bad smells” in code
Covered several examples
April 17, 2003 © University of Colorado, 2003 4
Goals for this lecture
Present a more complete tutorial on
refactoring using a slightly larger example
that requires multiple refactorings
pf3
pf4
pf5
pf8

Partial preview of the text

Download Refactoring Tutorial: Part 2 - Improving Code Design with Martin Fowler's Techniques and more Study notes Computer Science in PDF only on Docsity!

Lecture 28: Refactoring (part 2)

Kenneth M. Anderson

Object-Oriented Analysis and DesignCSCI 6448 - Spring Semester, 2003

April 17, 2003 © University of Colorado, 2003

Credit where Credit is Due^ 

Some of the material for this lecture andlecture 25 is taken from “Refactoring:Improving the Design of Existing Code”by Martin Fowler; as such somematerial is copyright © Addison Wesley, 1999

April 17, 2003 © University of Colorado, 2003

Last Lecture^ 

Refactoring^ 

Introduced core ideas

^

Improve design without changing functionality

^

Watch out for “bad smells” in code

^

Covered several examples

April 17, 2003 © University of Colorado, 2003

Goals for this lecture^ 

Present a more complete tutorial onrefactoring using a slightly larger examplethat requires multiple refactorings

April 17, 2003 © University of Colorado, 2003

Tutorial^ 

A simple program for a video store^ 

Movie

^

Rental

^

Customer

^

customer object can print a statement (in ASCII)

^

We’d like to modify the code to also print a statementin HTML and have discovered that none of theexisting code can be reused!

^

See example code (available on class website)^ 

Added a test case! We will test our code after eachrefactoring

April 17, 2003 © University of Colorado, 2003

Does this code need refactoring?^ 

For such a simple system^ 

probably not

but imagine that these three classes are partof a larger system^ 

then the refactorings we do during the tutorial canindeed be useful

^

the point is to imagine following this process on a dailybasis in a larger system project

^

refactoring needs to be incremental, systematic, and safe

April 17, 2003 © University of Colorado, 2003

Initial Class Diagram

statement works by looping through all rentals;for each rental, it retrieves its movie and the number of daysit was rented; it also retrieves the price code of the movieit then calculates the price for each movie rental and thenumber of frequent renter points and returns the generatedstatement as a string; see page 4 of Refactoring

April 17, 2003 © University of Colorado, 2003

Step 1: refactor statement()^ 

Why? It’s a “long method” which is one of the“bad smells” presented in the last lecture

Besides, our purpose is to add a new methodto generate an HTML statement andrefactoring statement() may lead to code thatcan be reused by the new function^ 

This matches one of Fowler’s conditions forrefactoring: cleaning up the code to make itpossible to add a new function

April 17, 2003 © University of Colorado, 2003

Step 4: Replace Temp with Query^ 

In the statement() method, thisAmount is nowredundant. It is set once with the call toeach.getCharge() and is not changed afterward; letsget rid of it.^ 

Don’t forget to run your test!

^

Removing temp variables is a good thing, becausethey often cause the need for parameters wherenone are required and can also cause problems inlong methods;^ 

of course the charge is now calculated twice through theloop, but we can optimize the calculation later (but only if wedetermine that it is slowing us down)

April 17, 2003 © University of Colorado, 2003

Step 5: frequent renter points^ 

Lets do the same thing with the logic tocalculate frequent renter points^ 

Step 5a: extract method

^

each can be a parameter, as in step

^

frequentRenterPoints has a value before the method isinvoked, but the new method does not read it; we simplyneed to use appending assingment outside the method

^

Step 5b: move method

^

Again, we are only using information from Rental, notcustomer, so lets move getFrequentRenterPoints to theRental class

^

Be sure to run your test case after each step

April 17, 2003 © University of Colorado, 2003

New class diagram

Customer continues to get smaller, Rental continues to getlarger; but Rental now has operations that change it frombeing a “data holder” to a useful objectOur sequence diagram has changed (see page 25); statement()used to call the movie class to get the price code for each movie.Now rental takes care of that, and statement now calls methodsthat have names that mean something rather than presentingtons of code whose purpose may not be clear

April 17, 2003 © University of Colorado, 2003

Step 6: Remove temp variables^ 

statement() still has temp variables^ 

totalAmount and frequentRentalPoints

Both of these values are going to be neededby statement() and htmlStatement()^ 

Lets replace them with query methods

^

little more difficult because they were calculated within aloop; we have to move the loop to the query methods

^

Step 6a: replace totalAmount

^

Step 6b: replace frequentRentalPoints

^

test after each step

April 17, 2003 © University of Colorado, 2003

Current class diagram

Customer class is now bigger; but has two methods that canbe shared with the existing statement() method and the plannedhtmlStatement() methodOur sequence has again changed, see page 31, because now wehave three loops instead of one; again, performance can be aconcern but we should wait until a profiler tells us so!

April 17, 2003 © University of Colorado, 2003

Step 7: add htmlStatement()^ 

We are now ready to add the htmlStatement()function^ 

Note: I’m not going to test this function, but I willadd it, so you can see how our refactorings so far,have made it easy to add this function

^

I added a file to the step7 directory that prints out theresults of calling htmlStatement(); you can send theoutput to a web browser if you want

^

You can actually improve these two methodsusing a refactoring called Form Template Method,but I will not cover that today

April 17, 2003 © University of Colorado, 2003

New Requirements^ 

It is now anticipated that the store is going tohave more than the three initial types ofmovies;^ 

as a result of these new classifications, renterpoints and charges will vary with each new movietype

^

as a result, we should probably move thegetCharge() and getFrequentRenterPoints()methods to the Movie class

April 17, 2003 © University of Colorado, 2003

Step 8: move methods^ 

Step 8a: move getCharge to Movie^ 

getCharge needs to know the number ofdays the movie was rented; since this isinformation that Rental has, it needs to bepassed a parameter

Step 8b: movegetFrequentRenterPoints() to Movie^ 

ditto!

April 17, 2003 © University of Colorado, 2003

Step 10: Move Method^ 

Now we need to move the methodgetCharge to the newly created Priceclass^ 

It’s a very simple move, we just need toremember to change Movie to delegate itsgetCharge operation to Price

April 17, 2003 © University of Colorado, 2003

Step 11: Replace Conditionalwith Polymorphism^ 

Now, we move each branch of the switchstatement into the appropriate subclass^ 

I do this in one move; Fowler actuallyrecommends moving one branch at a time, andintroducing a bug, so you can be sure that thesubclass’s method is the one being invoked!

After you have done the move, changePrice’s getCharge to an abstract method

Don’t forget to test; everything still works!

April 17, 2003 © University of Colorado, 2003

Step 12: handle renter points^ 

Now we repeat step 10 and 11, this timeapplying them to frequent renter points

I combine both steps into one^ 

we move the method over to price, and usepolymorphism to handle the logic

^

note: this time we leave a default implementation in Priceand have newRelease override that implementation,since it is the only class that returns a different value

Run the test and everything still works!

April 17, 2003 © University of Colorado, 2003

We’re done!^ 

We’ve added new functionality,changed “data holders” to “objects” andmade it very easy to add new types ofmovies with special charges andfrequent rental points

The final version of the code is in the after

directory; compile it and run the

test: test passed!

April 17, 2003 © University of Colorado, 2003

Final class diagram

Note: not all methodsand attributes are shown;getFRP is an abbreviationof getFrequentRenterPointsSee page 51 forfinal sequencediagram

April 17, 2003 © University of Colorado, 2003

What’s Next?^ 

Now that we have covered designpatterns and refactoring, we will nextlook at test-driven design and object-oriented design heuristics^ 

Recall that a heuristic is a rule of thumb; anoo design heuristic is a rule of thumb thatcan help us distinguish between “bad” OOdesigns and “good” OO designs