[Tutor] Refactoring
Steven D'Aprano
steve at pearwood.info
Thu Mar 8 15:06:23 CET 2012
Ejaj Hassan wrote:
> Hi,
> I have been hearing this refactoring of code. Well does it have
> any thing like this in Python and if it is then what is it all about.
"Refactoring" is a general technique that applies to any language, not just
Python. Refactoring means to take a program which is written in a complicated
way, not easy to understand, and gradually simplify it so that it becomes
easier to understand and maintain without starting from scratch or changing
the behaviour.
The trick with refactoring is to find parts of the program that have common,
related code. Here is a toy example -- suppose I had code that looks like this:
# Ask the user for a number between one and ten.
print "Please enter a number between 1 and 10"
while True:
a = int(raw_input("My number is: "))
if 1 <= a <= 10:
break
print "I'm sorry, your number was not between 1 and 10"
print "please try again"
# Ask the user for a number between ten and twenty.
print "Please enter a number between 10 and 20"
while True:
b = int(raw_input("My number is: "))
if 10 <= a <= 20:
break
print "I'm sorry, your number was not between 10 and 20"
print "please try again"
# And one more between twenty and 100.
print "Please enter a number between 20 and 100"
while True:
c = int(raw_input("My number is: "))
if 20 <= c <= 100:
break
print "I'm sorry, your number was not between 1 and 10"
print "please try again"
print a+b+c
Look at all that duplicated code! And if you look carefully, you'll see a
silly bug in it as well.
You might re-factor that code like so:
def get_number(low, high):
# Ask the user for a number between low and high.
print "Please enter a number between", low, "and", high
while True:
n = int(raw_input("My number is: "))
if low <= n <= high:
break
print "I'm sorry, your number was not between", low, "and", high
print "please try again"
return n
a = get_number(1, 10)
b = get_number(10, 20)
c = get_number(20, 100)
print a+b+c
Notice that in refactoring, the aim should be to end up with code that is
easier to maintain in the future. In this example, all the repeated code is
now in one place, so instead of having to make changes to it in three
different places, we can make it in one place.
--
Steven
More information about the Tutor
mailing list