A design problem I met again and again.

Jorgen Grahn grahn+nntp at snipabacken.se
Thu Apr 2 18:11:56 CEST 2009


[top-posting fixed]

On Thu, 2 Apr 2009 08:02:23 -0700 (PDT), =?GB2312?B?0rvK18qr?= <newptcai at gmail.com> wrote:
> On Apr 2, 5:58 am, Carl Banks <pavlovevide... at gmail.com> wrote:
>> On Apr 1, 12:44 am, ?????? <newpt... at gmail.com> wrote:
>>
>> > I got the same problem when writing C#/C++ when I have to provide a
>> > lot of method to my code's user.  So I create a big class as the entry
>> > point of my code.  Although these big classes doesn't contains much
>> > logic,  they do grow bigger and bigger.
>>
>> This seems to be a classic result of "code-based organization", that
>> is, you are organizing your code according to how your functions are
>> used.  That's appropriate sometimes.  Procedural libraries are often
>> organized by grouping functions according to use.  The os module is a
>> good example.
>>
>> However, it's usually much better to organize code according to what
>> data it acts upon: "data-based organization".  In other words, go
>> though your big class and figure out what data belongs together
>> conceptually, make a class for each conceptual set of data, then
>> assign methods to classes based on what data the methods act upon.
>>
>> Consider the os module again.  It's a big collection of functions, but
>> there are a group of functions is os that all act on a particular
>> piece of data, namely a file descriptor.  This suggests tha all the
>> functions that act upon file descriptors (os.open, os.close, os.seek,
>> etc.) could instead be methods of a single class, with the file
>> descriptor as a class member.
...

> 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.

If that's true, then your problems are not surprising.
A real class normally doesn't get that big.

> About the "data-based" approach, what if these functions all shares a
> little data, e.g. a socket, but nothing else?

If that is true, then those functions *are* the Python socket class
and everything has already been done for you.

Turn your question around and it makes more sense (to me, at least).
You don't primarily work with functions: you work with data, a.k.a.
state, a.k.a. objects.  The functions follow from the data.

To me, if I can find something with a certain lifetime, a certain set
of invariants, and a suitable name and catchphrase describing it, then
that's probably a class. Then I keep my fingers crossed and hope it
works out reasonably well. If it doesn't, I try another approach.

/Jorgen

-- 
  // Jorgen Grahn <grahn@        Ph'nglui mglw'nafh Cthulhu
\X/     snipabacken.se>          R'lyeh wgah'nagl fhtagn!



More information about the Python-list mailing list