A design problem I met again and again.

Carl Banks pavlovevidence at gmail.com
Wed Apr 1 23:58:55 CEST 2009

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.

(Note: the os library doesn't do that because functions like os.open
are supposed to represent low-level operations corresponding to the
underlying system calls, but never mind that. Ordinarily a bunch of
functions operating on common data should be organized as a class.)

Carl Banks

More information about the Python-list mailing list