In part 1 of this series, I reimplemented the Video Store exercise in Pharo Smalltalk, this didn’t take long, it’s not many lines of code.

On to the refactoring…

Extracting the amount calculation

The first step, is to extract the logic that calculates the price of a Rental.

Customer >> amountFor: aRental [
	"I calculate the cost to rent the movie for a period."

	| thisAmount |
	thisAmount := 0.
	aRental movie priceCode = #regular ifTrue: [ thisAmount := thisAmount + 2 ].
	(aRental movie priceCode = #regular and: [ aRental daysRented > 2 ]) 
		ifTrue: [ thisAmount := thisAmount + (aRental daysRented - 2 * 1.5) ].

	aRental movie priceCode = #new ifTrue: [ 
		thisAmount := thisAmount + aRental daysRented * 3 ].

	aRental movie priceCode = #childrens ifTrue: [ 
		thisAmount := thisAmount + 1.5 ].
	(aRental movie priceCode = #childrens and: [ aRental daysRented > 3 ]) 
		ifTrue: [ thisAmount := thisAmount + (aRental daysRented - 3) * 1.5 ].
	^ thisAmount
]

This leads to a small change in the statement method:

		  rentals do: [ :rental | 
			  thisAmount := self amountFor: rental.

All the tests pass at this point.

Tests passing

At this point in the book, Fowler talks about the Smalltalk refactoring browser, and how he was “looking forward to a Java version!”. I’ll be honest, the state of the art in refactoring tools is definitely now in the Java camp.

But Pharo does have a refactoring browser, so, I reverted the change above and used it:

Selecting the code to be refactored

Creating the method

This lead to the same result (minus the comment of course).

Refactored method

Renaming result

The next step is renaming thisAmount to result.

This is trivial with the refactoring browser (although, ‘Rename temp’ is not obvious).

Rename temp

Enter the new name

This was a nice step forward.