A design problem I met again and again.

paul paul at subsignal.org
Fri Apr 3 20:02:39 CEST 2009


一首诗 schrieb:
> 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
> #=========================
> 
> But isn't the first style more clear for my code's user?
Depends ;)

There are more ways to structure code than using classes. To avoid the
if-elif-elif-elif-else problem you could start using a dispatch table
which maps types to functions (fex using a dict)

start_methods = {
 'type1': startXX,
 'type2': startYY,
}

def start(type, id):
  func = start_methods.get(type, None)
  if func:
    func(id)
  else:
    raise ...

Or maybe look at trac's (http://trac.edgewall.com) use of Components and
Interfaces. Very lightweight and modular. You can start reading here:
http://trac.edgewall.org/browser/trunk/trac/core.py

cheers
 Paul

> 
> That's one reason why my interfaces grow fast.
> 
> On Apr 3, 1:51 am, Carl Banks <pavlovevide... at gmail.com> wrote:
>> On Apr 2, 8:02 am, 一首诗 <newpt... at gmail.com> wrote:
>>
>>> You get it.  Sometimes I feel that my head is trained to work in a
>>> procedural way.  I use a big class just as a container of functions.
>>> About the "data-based" approach, what if these functions all shares a
>>> little data, e.g. a socket, but nothing else?
>> Then perhaps your problem is that you are too loose with the
>> interface.  Do you write new functions that are very similar to
>> existing functions all the time?  Perhaps you should consolidate, or
>> think about how existing functions could do the job.
>>
>> Or perhaps you don't have a problem.  There's nothing wrong with large
>> classes per se, it's just a red flag.  If you have all these functions
>> that really all operate on only one piece of data, and really all do
>> different things, then a large class is fine.
>>
>> Carl Banks
> 
> --
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list