Maintaining Your Programs

Okay, you've written your program. Now what? Chances are you'll want to make some changes soon. In fact, most programmers spend far more time changing existing programs than writing new ones. When you want to update your code, you'll likely be tempted to change it in a way that doesn't take a lot of time. But that might not be the best way to go about it in the long run.

Suppose you've written a program to send yourself a daily e-mail with the top ten lines from your calendar file. It might look like Listing 5-1.

Listing 5-1: daily calendar.py_

import smtplib # get the module for sending email my address = '[email protected]' headers = [ 'Subject: Daily calendar', 'From: ' + my address, 'To: ' + my address,

] # this list spans four lines for readability entries = open('my calendar').

msg = '\r\n'.join(headers) + '\r\n' + ''.join(entries)

smtp = smtplib.SMTP('mail') # replace 'mail' with the name of your mailhost smtp.sendmail(my address, [my address], msg) smtp.close()

Then you decide you want to send yourself a bigger chunk once a week. The simple, easy —and wrong—way to do it, illustrated in Listing 5-2, is called cut-'n'-paste programming. Note how most of the lines of the program are repeated in the if and else statements. (By the way, another change made in the program was the addition of sys.argv to get a command-line argument. That's not bad programming, we just wanted to point it out.)

Listing 5-2: calendar.py_

import smtplib, sys my address = '[email protected]' if sys.argv[1] == 'weekly':

headers = [ 'Subject: Weekly calendar', 'From: ' + my address,

entries = open('my calendar').

msg = '\r\n'.join(headers) + ''.join (entries) smtp = smtplib.SMTP('mail')

smtp.sendmail(my address, [my address], msg) smtp.close()

else:

headers = [ 'Subject: Daily calendar', 'From: ' + my address,

entries = open('my calendar').readlines()[:10] msg = '\r\n'.join(headers) + ''.join(entries) smtp = smtplib.SMTP('mail')

smtp.sendmail(my address, [my address], msg) smtp.close()

The right way to upgrade your code avoids this repetition by taking the repeated code and turning it into a chunk that gets called by another part of the program. This is called refactoring the code.

Tip If you remember algebra, code refactoring is similar to algebraic factoring; for example, breaking the number 12 into its factors 3 x 4.

Refactoring a program works like this:

Was this article helpful?

0 0

Post a comment