Functional vs. Object oriented API

Roy Smith roy at panix.com
Fri Apr 12 10:19:47 EDT 2013


In article <51678b94$0$29977$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> - If you have a complicated interface, or data with complicated internal 
> state, the best solution is to use a custom object with methods.
> 
> - But if your interface is simple, and the data is simple, it is more 
> efficient to stick to lightweight built-ins [...]
> 
> - If the *only* reason you use a class is to keep the data together, 
> that's very much a Java design.

As part of our initial interview screen, we give applicants some small 
coding problems to do.  One of the things we see a lot is what you could 
call "Java code smell".  This is our clue that the person is really a 
Java hacker at heart who just dabbles in Python but isn't really fluent.  
It's kind of like how I can walk into a Spanish restaurant and order 
dinner or enquire where the men's room is, but everybody knows I'm a 
gringo as soon as I open my mouth.

It's not just LongVerboseFunctionNamesInCamelCase().  Nor is it code 
that looks like somebody bought the Gang of Four patterns book and is 
trying to get their money's worth out of the investment.  The real dead 
giveaway is when they write classes which contain a single static method 
and nothing else.

That being said, I've noticed in my own coding, it's far more often that 
I start out writing some functions and later regret not having initially 
made it a class, than the other way around.  That's as true in my C++ 
code as it is in my Python.

In my mind, classes are all about data.  If there's no data (i.e. no 
stored state), you should be thinking a collection of functions.  On the 
other hand, if there's ONLY data and no behavior, then you should be 
thinking namedtuple (which is really just a shortcut way to write a 
trivial class).

Once you start having state (i.e. data) and behavior (i.e. functions) in 
the same thought, then you need a class.  If you find yourself passing 
the same bunch of variables around to multiple functions, that's a hint 
that maybe there's a class struggling to be written.



More information about the Python-list mailing list