critic this please

Quinn Dunkan quinn at yak.ugcs.caltech.edu
Thu Jun 21 16:28:28 EDT 2001


On Thu, 21 Jun 2001 10:09:00 -0500, NJM <njm at rectec.net> wrote:
>I've just wrote this small program that calculates the length of a rafter
>for you(I'm a carpenter), but I didn't write it "properly".  I can't seem to
>wrap my head around using classes.  Does anyone have any input.
>
>
> import Tkinter
>
>def fig5():
>  a = float(Tkinter.Entry.get(feet))
>  b = float(Tkinter.Entry.get(inch))
>  Tkinter.Entry.delete(answer, 0, 20)
>  Tkinter.Entry.insert(answer, 0, (b/12 + a)*13)
>
>def fig6():
>  a = float(Tkinter.Entry.get(feet))
>  b = float(Tkinter.Entry.get(inch))
>  Tkinter.Entry.delete(answer, 0, 20)
>  Tkinter.Entry.insert(answer, 0, (b/12 + a)*13.42)
[ etc. ]

Since these only differ by their multiplier, I'd say something like:

fig_map = {
    5 : 13,
    6 : 13.42,
    7 : 13.89,
    8 : 14.42,
    ...
}

def fig(n):
    a = float(Tkinter.Entry.get(feet))
    b = float(Tkinter.Entry.get(inch))
    Tkinter.Entry.delete(answer, 0, 20)
    Tkinter.Entry.insert(answer, 0, (b/12 + a) * fig_map[n])


.. and then replace this

>button=Tkinter.Button(frame2, text="'5-12'", command=fig5)
>button.pack(side=Tkinter.LEFT)
>button2=Tkinter.Button(frame2, text="'6-12'", command=fig6)
>button2.pack(side=Tkinter.LEFT)
[ etc. ]

with:

for n in range(5, 13): # note range() doesn't include the last number
    b = Tkinter.Button(frame2, text="'%d-12'" % n, command=lambda n=n: fig(n))
    b.pack(side=Tkinter.LEFT)


Note that 'lambda n=n: fig(n)' is a python idiom that makes a function that
evaluates 'fig(n)' (where 'n' is whatever 'n' happened to be when the lambda
was evaluated).


In general, whenever you find yourself doing something repetitive, you're
doing work that the computer could be doing for you.  Your job is to capture
the changing bits (such as the multiplier mapping), factor them out, and write
code to do all the tedious work.  How easy it is to factor bits out is a
measure of the flexibility of a language.

And if you find yourself with names like 'foo1', 'foo2', etc., chances are
you're either doing something repetitive, or not giving very descriptive
names.

And it's perfectly possible to write lots of 'proper' python without any
classes at all.



More information about the Python-list mailing list