[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

update the HTML, too). More generally, there are a handful of ways that this program
might fail the scrutiny of a rigorous code review:


Selection list
As just mentioned, the list of languages supported by this program lives in two
places: the HTML file and the CGI script’s table, and redundancy is a killer for
maintenance work.


Field name
The field name of the input parameter, language, is hardcoded into both files as
well. You might remember to change it in the other if you change it in one, but you
might not.


Form mock-ups
We’ve redundantly coded classes to mock-up form field inputs twice in this chapter
already; the “dummy” class here is clearly a mechanism worth reusing.


HTML code
HTML embedded in and generated by the script is sprinkled throughout the pro-
gram in print call statements, making it difficult to implement broad web page
layout changes or delegate web page design to nonprogrammers.


This is a short example, of course, but issues of redundancy and reuse become more
acute as your scripts grow larger. As a rule of thumb, if you find yourself changing
multiple source files to modify a single behavior, or if you notice that you’ve taken to
writing programs by cut-and-paste copying of existing code, it’s probably time to think
about more rational program structures. To illustrate coding styles and practices that
are friendlier to maintainers, let’s rewrite (that is, refactor) this example to fix all of
these weaknesses in a single mutation.


Step 1: Sharing Objects Between Pages—A New Input Form


We can remove the first two maintenance problems listed earlier with a simple trans-
formation; the trick is to generate the main page dynamically, from an executable script,
rather than from a precoded HTML file. Within a script, we can import the input field
name and selection list values from a common Python module file, shared by the main
and reply page generation scripts. Changing the selection list or field name in the com-
mon module changes both clients automatically. First, we move shared objects to a
common module file, as shown in Example 15-19.


Example 15-19. PP4E\Internet\Web\cgi-bin\languages2common.py


"""
common objects shared by main and reply page scripts;
need change only this file to add a new language.
"""


inputkey = 'language' # input parameter name


Refactoring Code for Maintainability | 1193
Free download pdf