-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmostly-pointless.html
270 lines (236 loc) · 11.1 KB
/
mostly-pointless.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
<html>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<head>
<title>
leontrolski - OO in Python is mostly pointless
</title>
<style>
body {margin: 5% auto; background: #fff7f7; color: #444444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.8; max-width: 63%;}
@media screen and (max-width: 800px) {body {font-size: 14px; line-height: 1.4; max-width: 90%;}}
pre {width: 100%; border-top: 3px solid gray; border-bottom: 3px solid gray;}
a {border-bottom: 1px solid #444444; color: #444444; text-decoration: none; text-shadow: 0 1px 0 #ffffff; }
a:hover {border-bottom: 0;}
.inline {background: #b3b2b226; padding-left: 0.3em; padding-right: 0.3em; white-space: nowrap;}
blockquote {font-style: italic;color:black;background-color:#f2f2f2;padding:2em;}
details {border-bottom:solid 5px gray;}
</style>
<link href="https://unpkg.com/[email protected]/themes/prism-vs.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/components/prism-core.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/plugins/autoloader/prism-autoloader.min.js">
</script>
</head>
<body>
<a href="index.html">
<img src="pic.png" style="height:2em">
⇦
</a>
<p><em>Part of a series - <a href="index.html#stop">Stop doing things</a></em></p>
<br>
<p><i>2021-01-27</i></p>
<h1>
OO in Python is mostly pointless
</h1>
<p>
<em>
Discussion <a href="https://news.ycombinator.com/item?id=25933121">
here
</a>
and <a href="https://lobste.rs/s/ldzfsw/oo_python_is_mostly_pointless">
here
</a>
. Call to arms for idiomatic OO code <a href="https://github.com/leontrolski/call-to-arms">
here
</a>
.
</em>
</p>
<p>
People bash OO a lot these days, I'm increasingly coming to the opinion they're right, at least in Python. My point here is not to argue that OO is bad per se, more that its introduction is simply unnecessary, AKA not useful.
</p>
<h2>
Oli's Conjecture
</h2>
<blockquote>
All OO code can be refactored into equivalent non-OO code that's as easy or more easy to understand.
</blockquote>
<p>
Let's take an example that should pan out in OO's favour, we've all seen/written code somewhat like the following:
</p>
<pre class="language-python"><code>class ApiClient:
def __init__(self, root_url: str, session_cls: sessionmaker):
self.root_url = root_url
self.session_cls = session_cls
def construct_url(self, entity: str) -> str:
return f"{self.root_url}/v1/{entity}"
def get_items(self, entity: str) -> List[Item]:
resp = requests.get(self.construct_url(entity))
resp.raise_for_status()
return [Item(**n) for n in resp.json()["items"]]
def save_items(self, entity: str) -> None:
with scoped_session(self.session_cls) as session:
session.add(self.get_items(entity))
class ClientA(ApiClient):
def construct_url(self, entity: str) -> str:
return f"{self.root_url}/{entity}"
class ClientB(ApiClient):
def construct_url(self, entity: str) -> str:
return f"{self.root_url}/a/special/place/{entity}"
client_a = ClientA("https://client-a", session_cls)
client_a.save_items("bars")</code>
</pre>
<p>
We chose OO it because we wanted to bind the <code class="inline">root_url</code>
to something and we didn't want to pass around the <code class="inline">sessionmaker</code>
. We also wanted to utilise inheritance to hook into a method halfway through the call stack.
</p>
<p>
But what if we do just pass data around, and write 'boring' functions, what happens then?
</p>
<pre class="language-python"><code>@dataclass
class Client:
root_url: str
url_layout: str
client_a = Client(
root_url="https://client-a",
url_layout="{root_url}/{entity}",
)
client_b = Client(
root_url="https://client-b",
url_layout="{root_url}/a/special/place/{entity}",
)
def construct_url(client: Client, entity: str) -> str:
return client.url_layout.format(root_url=client.root_url, entity=entity)
def get_items(client: Client, entity: str) -> List[Item]:
resp = requests.get(construct_url(client, entity))
resp.raise_for_status()
return [Item(**n) for n in resp.json()["items"]]
def save_items(client: Client, session_cls: session_cls, entity: str) -> None:
with scoped_session(session_cls) as session:
session.add(get_items(client, entity))
save_items(client_a, session_cls, "bars")</code>
</pre>
<p>
We had to pass round the <code class="inline">Client</code>
and the <code class="inline">session_cls</code>
around.
</p>
<p>
🤷
</p>
<p>
Who cares? We even wrote like 10% fewer characters. Also, the conjecture stands, the resulting code is at least as easy to understand and we didn't need any OO.
</p>
<p>
I've heard this style referred to as the <b>
bag-of-functions
</b>
style. That is to say, all your code just consists of typed data and module-namespaced-bags-of-functions.
</p>
<h2>
What about long lived global-y things?
</h2>
<p>
Use <a href="sane-config.html">
this pattern
</a>
to reuse config/db session classes over the lifetime of an application.
</p>
<h2>
What about interfaces/abstract base classes?
</h2>
<p>
Just try writing without them, I promise it's going to be OK. <em>
(To be fair, it's only the introduction of type hints to Python that has made the <b>
bag-of-functions
</b>
style so pleasant).
</em>
</p>
<h2>
What about impure things?
</h2>
<p>
If you've taken the pure-FP/hexagonal-architecture pill, you want to write pure classes that take impure 'adapter' instances for <code class="inline">getting-the-current-datetime/API-calls/talking-to-the-db/other-impure-stuff</code>
. The idea is nice in principle - should be good for testing right? - in practice, you can just use <a href="https://github.com/spulec/freezegun">
freezegun
</a>
/ use <a href="https://github.com/getsentry/responses">
responses
</a>
/ <a href="https://dhh.dk/2014/slow-database-test-fallacy.html">
test with the db
</a>
(the <code class="inline">other-impure-stuff</code>
tends to not actually exist) and save yourself a lot of hassle.
</p>
<h2>
Exceptions:
</h2>
<p>
I'd like to make exceptions for the following:
</p>
<ul>
<li>
You'll notice I put <code class="inline">@dataclass</code>
s in the refactored code, these are fine - they're just record types. Python 5 will only have these, not 'normal' classes.
</li>
<li>
It's fine to subclass <code class="inline">Exception</code>
s. The usage of <code class="inline">try: ... except SomeClass: ...</code>
fundamentally ties you to a heirarchical worldview, this is fine, just don't make it too complicated.
</li>
<li>
<code class="inline">Enum</code>
s - same as above, they fit in well with the rest of Python.
</li>
<li>
Very, very occasionally (at least in application development), you come up with a core type that's used so often, it's nice to have the cutesy stuff - think something like a <code class="inline">pandas.DataFrame</code>
/ <code class="inline">sqlalchemy.Session</code>
. In general though, don't kid yourself that you're building anything that exciting, it's just vanity getting the better of you.
</li>
</ul>
<h2>
I lied.
</h2>
<blockquote>
My point here is not to argue that OO is bad per se.
</blockquote>
<p>
OK, I lied, it's not just a case of OO being a largely futile addition to the language, it's that it often obscures the problem at hand and encourages bad behaviours:
</p>
<ul>
<li>
It encourages you to mutate. Bag-of-functions makes it feel icky to mutate arguments - as it should feel. (Feel free to mutate within the confines of your function BTW, let's not go mad FP).
</li>
<li>
It's somewhat just the return of global variables. Not being able to share data between functions with <code class="inline">self</code>
forces you to write functions with a smaller state-space that are easier to test.
</li>
<li>
Smooshing functions in with your data makes it harder to serialise anything - in a world of REST APIs, serialisability is super useful.
</li>
<li>
It encourages mad inheritance hierarchies - this has been talked about at length elsewhere.
</li>
<li>
Most importantly though, it adds nothing, it's just noise that distracts from the problem at hand and makes it harder to navigate/comprehend your code.
</li>
</ul>
<h2>
Notes
</h2>
<ul>
<li>
<a href="poor-mans-object.html">
I've written before about the poor man's object/closure thingy.
</a>
</li>
<li>
<a href="https://www.youtube.com/watch?v=o9pEzgHorH0">
A classic video in the OO-bashing genre.
</a>
</li>
</ul>
</body>
</html>