switch
Asun Friere
afriere at yahoo.co.uk
Wed Dec 9 20:02:22 EST 2009
On Dec 9, 7:08 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
> What if the object is a string you just read from a file?
>
> How do you dispatch using polymorphism in that case?
This would be a pertinent question, were I advocating that _all_
switch statements should, or even can, be replaced with "dispatch
using polymorphism."
What if, instead of reading strings from a file, you are parsing, say
xml, into an object framework isomorphic to the file's schema? And
no, this is not a contrived example. Now you want to print out the
structure, or a branch thereof. To make matters interesting you want
to be able to print it out in a number of different formats. So we
have:
5 def print_out (element, fmnt) :
6 if element.__class__ is schema.Title :
7 if str(fmnt) == 'html' :
8 print_out_spam_title(element)
9 elif str(fmnt) == 'txt' :
10 print_out_ham_title(element)
11 elif ....
12 elif element.__class__ is schema.Paragraph :
13 if str(fmnt) == 'html' :
14 print_out_spam_paragraph(element)
15 elif str(fmnt) == 'txt' :
16 print_out_ham_paragraph(element)
17 elif ...
18 elif element.__class__ is ...
19 ...
20
And so on for a dozen or so tags and 3 formats. And imagine the joy
of adding the 4th or 5th format.
Now I guess you already realise that applying a dispatch mechanism
here will improve the design and result in code that is dryer, far
more easily extensible and arguably (but only arguably) more readible?
More information about the Python-list
mailing list