A design problem I met again and again.
andrew cooke
andrew at acooke.org
Sat Apr 4 08:29:40 EDT 2009
Note sure who wrote:
>> > Consolidate existing functions?
>>
>> > I've thought about it.
>>
>> > For example, I have two functions:
>>
>> > #=========================
>>
>> > def startXXX(id):
>> > pass
>>
>> > def startYYY(id):
>> > pass
>> > #=========================
>>
>> > I could turn it into one:
>>
>> > #=========================
>> > def start(type, id):
>> > if(type == "XXX"):
>> > pass
>> > else if(type == "YYY"):
>> > pass
>> > #=========================
in general, if you are testing type that is an indication you should
refactor to use a base class with subclassing.
for example:
def my_print(x):
print 'i have a ',
if type(x) is Foo:
print 'furry foo'
elif type(x) is Bar:
print 'bubbly Bar;
else:
print 'strange beast'
might be refactored as
class MyPrintable(object):
def my_print(self):
print 'i have a ', self.describe()
class Foo(MyPrintable):
def describe(self):
return 'furry Foo'
etc etc.
it's not always possible, but any type() or isinstance() in an OO program
is a big red flag that the design is wrong.
andrew
More information about the Python-list
mailing list