[Tutor] I don't get it

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 20 Sep 2002 22:29:09 -0700 (PDT)


On Sat, 21 Sep 2002, Kirk Bailey wrote:

> OK, I think I detected a burned out light bulb.
>
> See, I absorbed all this the eclectic way, no schooling. There's
> probably holes all through my brain regarding computing.
>
> Tell me about factoring please?

Hi Kirk,

"Factoring" as a programming technique isn't too hard to understand: it's
just the teasing out of a chunk of code from a program and giving it a
good name as a function.  For example, if we saw something like this:

###
print "Hey, what's your name? ",
name = raw_input()

print "And what's your age? ",
age = raw_input()
###


we could look at both blocks, and try making a function that takes the
best of the common elements:

###
def askAQuestion(question):
    print question, " ",
    return raw_input()

name = askAQuestion("Hey, what's your name?")
age = askAQuestion("And what's your age?")
###

Programmers who want to sound learned and wise by call this "factoring",
but this amazing technique is just moving code around.  Or is it?  The
"Refactoring" folks say that this grouping and regrouping of code is
really important if we want to make good programs.


There's an initial cost into making this function --- what we have now is
a little bit longer.  However, any new questions that we want to ask can
use our askQuestion() function, so instead of writing those two
print/raw_input() statements again, we can askAQuestion().


Do you have the latest version of your mail list program?  Perhaps we can
kill two birds with one stone, and do a concrete factoring of your program
into functions.


Talk to you later!