osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Style Q: Instance variables defined outside of __init__


On Wed, Mar 21, 2018 at 2:15 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Tue, 20 Mar 2018 11:14:13 +0000, Alister via Python-list wrote:
>
>> but why would a functional programmer be programming an OOP class?
>
> I read a really good blog post a while back, which I sadly can no longer
> find (I had it bookmarked until Firefox ate my bookmarks) that discussed
> exactly that question.
>
> What they came up with is that its really hard to do useful work for
> large applications with 100% pure functional programming styles. As you
> add functional techniques to your code, you find your code quality
> increasing. Things like pure functions with no hidden state and no side
> effects can have a massive positive effect on code quality -- up to a
> point.
>
> As you approach closer and closer to 100% pure functional code, you get
> fewer improvements and your code gets harder to write and maintain.
>
> He maintains that the sweet spot is about 80% functional, and 20% OOP.

Yep, I remember that article. Sadly, I can't find it back now either;
maybe someone can craft a regular expression to find it?
https://xkcd.com/208/

This week I dived into the source code for an application that's built
out of 20 Python files in four package directories plus a top-level
"app.py" as its entry point. You'd think that that means I can write
my own Python script that imports from those packages and calls on the
same code, right? Sadly, no; because this app is 100% OOP and 0%
functional. (Not to be confused with a *non-functioning* app; it
functions perfectly well. It just doesn't follow *functional
programming* idioms.) Deep inside the imported modules, a class's
__init__ will check command-line arguments to control its behaviour,
and in the event of a problem (eg JSON data lacking vital
information), will print a failure message and exit the program. Were
this class written in a pure functional style, it would use the
construction parameters, and raise an exception if something's wrong.
It's entirely possible for a class to follow functional programming
style, at least partly.

(In theory, it should be possible to use a class in a 100% functional
style. A class is just a callable function that then happens to return
a thing of a type that has the same name as the thing you called, so
there's no reason the two styles can't completely overlap.)

ChrisA