[Tutor] When to use classes

Peter Otten __peter__ at web.de
Sat Aug 19 05:04:33 EDT 2017


Steven D'Aprano wrote:

> Mostly for Bob, but also for anyone else interested:
> 
> When To Use Classes
> 
> http://kentsjohnson.com/stories/00014.html

Just a minor nit, but you don't even need a custom function for the callback

result = []
db.query(sql, result.append)

The lesson is that Python already provides some powerful ready-to-use 
classes that take you a long way without having to write your own custom 
classes.

Another alternative to (explicit) classes are generators which are an 
elegant way to hold state and provide a simple interface. 

In modern Python db.query() should be an iterable to that the above can be 
written

result = list(db.query(sql))

(That was easy; but I wonder what tkinter would look like without 
callbacks...)

> He says:
> 
>     You may have several functions that use the same state
>     variables, either reading or writing them. You are passing
>     a lot of parameters around. You have nested functions that
>     have to forward their parameters to the functions they use.
>     You are tempted to make some module variables to hold the
>     state.
> 
>     You could make a class instead!
> 
> 
> 
> Indeed you could, and sometimes you should, but we can see a problem
> here. The situation described is a bad situation to be in: there is too
> much coupling between functions, too much state being passed around.
> 
> Ideally we should try to *reduce the coupling* between components, if
> possible, and hence make the program less complex. OO design tries to
> encapsulate the coupling within (hopefully) a single class, but it does
> nothing to reduce the coupling or complexity.
> 
> So I would say:
> 
> - if your code is complex, with lots of connections between
>   components (coupling), try to reduce the coupling and make
>   the code simper;

Even if you can simplify the code with functions classes often give you a 
nicer interface. Nobody would want to write

a + b * c

as

add(a, mul(b, c))


> - if you can't, encapsulate it in classes.

I think it's important that you say "classes", not "class". As with 
functions three small dedicated classes are much better than one big know-
it-all/do-it-all class.



More information about the Tutor mailing list