A design problem I met again and again.

Carl Banks pavlovevidence at gmail.com
Sat Apr 4 00:10:30 EDT 2009


On Apr 2, 11:25 pm, 一首诗 <newpt... at gmail.com> 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
> #=========================
>
> But isn't the first style more clear for my code's user?

Not necessarily, especially if the user wants to dynamically choose
which start*** function to call.

I have one more suggestion.  Consider whether there are groups of
methods that are used together but aren't used with other groups of
functions.  For instance, maybe there is a group of methods that can
only be called after a call to startXXX.  If that's the case, you
might want to separate those groups into different classes.  The
branched-off class would then act as a sort of session handler.

A piece of user code that looked like this (where sc is an instance of
your enormous class):

sc.startX()
sc.send_data_via_X()
sc.receive_data_via_X()
sc.stopX()

might look like this after you factor it out:

session = sc.startX()  # creates and returns a new XSession object
session.send_data()    # these are methods of the XSession
session.receive_data()
session.stop()


Any methods that are callable any time, you can retain in the big
class, or put in a base class of all the sessions.


Carl Banks



More information about the Python-list mailing list