|
SandBox
Example of "extract method" refactorings - pseudocode
"before"
function Verylongmethod
begin
// set up foos
var foos = array [1..3] of foobar
foos[1] = new foobar(2,2,3,4)
foos[2] = new foobar(3,4,6,3)
foos[3] = new foobar(4,67,83,3)
// calculate muckiness
var muckiness = 0
for index = 1 to foos.length
muckiness = foos[ index ] . muckinessQuotient( index ) + muckiness
end for
return muckiness
end function
"after"
function setupfoos
var foos = array [1..3] of foobar
foos[1] = new foobar(2,2,3,4)
foos[2] = new foobar(3,4,6,3)
foos[3] = new foobar(4,67,83,3)
return foos
end function
function calculatemuckiness( foos )
var muckiness = 0
for index = 1 to foos.length
muckiness = foos[ index ] . muckinessQuotient( index ) + muckiness
end for
return muckiness
end function
function Verylongmethod
begin
var foos = setupfoos()
var muckiness = calculatemuckiness( foos )
return muckiness
end function
Now imagine that there is Anotherlongmethod similar to the original function Verylongmethod, where the only difference in how it sets up the foos array. It can be refactored to call the same calculatemuckiness method that had been extracted from Verylongmethod.
"before"
function Anotherlongmethod
begin
// set up foos
var foos = array [1..4] of foobar
foos[1] = new foobar(2,9,3,4)
foos[2] = new foobar(3,9,6,3)
foos[3] = new foobar(4,9,83,3)
foos[4] = new foobar(9,9,9,9)
// calculate muckiness
var muckiness = 0
for index = 1 to foos.length
muckiness = foos[ index ] . muckinessQuotient( index ) + muckiness
end for
return muckiness
end function
"after"
function setupfourfoos
var foos = array [1..4] of foobar
foos[1] = new foobar(2,9,3,4)
foos[2] = new foobar(3,9,6,3)
foos[3] = new foobar(4,9,83,3)
foos[4] = new foobar(9,9,9,9)
return foos
end function
function Anotherlongmethod
begin
var foos = setupfourfoos()
var muckiness = calculatemuckiness( foos )
return muckiness
end function
KeithRay 2003.06.03 (Edited by BobLee 2003.06.04)
Just tried some things out... CharlesAdams 2006.03.24
Did they work? DonGray 2006.03.25
Yes they did! CharlesAdams 2006-03-27
Updated: Monday, March 27, 2006
|