Using isA and getA in a python way

Jeremy Bowers jerf at jerf.org
Mon Sep 20 21:00:47 CEST 2004


On Mon, 20 Sep 2004 13:31:44 +0100, C Gillespie wrote:

> Dear All,
> 
> I have long list of if statements in the form of:
> 
> if obj.isA(): return obj.getA()
> if obj.isB(): return obj.getB()
> if obj.isC(): return obj.getC()
> if obj.isD(): return obj.getD()
> <snip>

This represents some concept in your mind. You don't tell us what it is,
but for example your concept might be "serialize":

if obj.isA(): return obj.serializeAsA()
if obj.isB(): return obj.serializeAsB()

Or any number of other things.

> Is there a nicer way of doing this, perhap going through the list
> ['A','B','C',..

For each of those obj types, assuming you control the class (which seems
likely), add a method that represents the *concept* you have in your head,
using that concept to name the method. This may take practice, and there
are a number of "code smells" (Google the term) that are associated with
this; the biggest one is that the harder it is to give the concept a name,
the more likely it is that your design needs more thinking. (This is not
an absolute.) Then, your sequence boils down to

obj.get()

or in my example,

obj.serialize()

Note that this new method is *in addition to* your current methods; "getA"
means something, and this new method on the class means something else,
even if it happens to be implemented in the same way and consist of
"return self.getA()" for the A object. 

If you give more details, people may be able to provide more specific help.



More information about the Python-list mailing list