[Tutor] Objectifying code

John Abbe johnca@ourpla.net
Tue Feb 4 01:41:14 2003


At 7:42 PM +0100 2003-01-24, Magnus Lycka wrote:
>To be honest, I didn't bother reading through the code well enough
>to understand what it did. This is partly because I'm in a hurry,
>and partly because it's written in a way that is difficult to read.
>
>I would suggest that you use the normal convention of python code,
>instead of writing something looking like an overgrown bat-file. ;)
>In other words, use the standard idiom of
>
>if __name__ == '__main__':
>     main()
>
>in the end, make a main() function that captures the main
>abstractions of the program, so that people can read that function
>(which is hopefully note more than a screenful) and understand
>what it's all about. You don't need classes for this, you can use
>well named functions.

This seems less readable to me, but i can see how it might make 
modularization more obvious (eg two functions doing almost identical 
things). Will do.

>I would also suggest that you remove all the big strings from the
>main body of the code. They completely mess up the readability that
>python normally provides. Let's have a look at a piece of code:

[...code with lots of long in-line strings...]

>I can't make myself try to follow this without giving
>it an overhaul.

...

>recordEditForm = """
><h1>Editing %(firstname)s %)(lastname)s's record</h1>
><form method=get action="%(cgiaddr)s">

[...edited for brevity...]

></form>"""
>
>The only thing left in the part of the program where I cut out
>this section would be:
>
>    elif 'edit' in Args:
>       # Edit a record
>       for entry in lankaDB:
>          if entry['firstname'] + entry['lastname'] == Args['edit']:
>             print recordEditForm % (entry + {'cgiaddr': cgiaddr})

Hm, my Python says "TypeError: unsupported operand types for +: 
'dict' and 'dict'"

So, i replaced that last line with:
             entry.update({'cgiaddr': cgiaddr})
             print recordEditForm % entry

(This only works because i don't mind altering the "entry" dict here. 
Is there a function that returns the merging of two dictionaries?)

>This is easier to read, isn't it? We don't have to worry about HTML
>form layout and program flow at the same time. The indentation is
>helpful in suggesting a structure, and the use of string % dict instead
>of string % tuple both cleans up the print statement and makes it
>much easier to modify and review the HTML forms.

B-b-b-b-b! Cool, i didn't know about the % dict trick with %(key)s. I 
guess that's why i'm on the python-newbies list :)

I'm re-working the code now and may re-submit it later for objectifying help...

Life,
John
-- 
  All you  /\/\ John Abbe           "If you don't like the news,
      need \  / CatHerder            go out and make some of your own."
      is... \/  http://ourpla.net/john/                --Wes Nisker