Debian Codegraph @

www/src/content/essays/codin-dirty.mdx

raw
1 ---
2 title: "Codin' Dirty"
3 description: "In this article, Carson Gross discusses an alternative approach to software development that challenges the principles outlined in 'Clean Code.' Carson advocates for allowing larger functions in certain cases, preferring integration tests over unit tests, and minimizing the number of classes and interfaces. He shares examples from successful software projects that demonstrate these practices can lead to maintainable, high-quality code."
4 created: 2024-11-24
5 modified: 2024-11-24
6 authors: ["Carson Gross"]
7 tags: ["simplicity"]
8 ---
9
10 import { Image } from 'astro:assets';
11 import quickAndDirty from '../../assets/img/quick-and-dirty.png';
12 import cleanVDirty from '../../assets/img/clean-v-dirty.png';
13
14 <Image src={quickAndDirty} alt="quick-and-dirty" />
15
16 > “Writing clean code is what you must do in order to call yourself a professional. There is no reasonable excuse for
17 > doing anything less than your best.” [Clean Code](https://www.goodreads.com/book/show/3735293-clean-code)
18
19 In this essay I want to talk about how I write code. I am going to call my approach "codin' dirty" because I often
20 go against the recommendations
21 of [Clean Code](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882),
22 a popular approach to writing code.
23
24 Now, I don't really consider my code all that dirty: it's a little gronky in places but for the most part I'm
25 happy with it and find it easy enough to maintain with reasonable levels of quality.
26
27 I'm also *not* trying to convince *you* to code dirty with this essay. Rather, I want to
28 show that it is possible to write reasonably successful software this way and, I hope, offer some balance around
29 software
30 methodology discussions.
31
32 I've been programming for a while now and I have seen a bunch of different approaches to building software work. Some
33 people love Object-Oriented Programming (I like it), other very smart people hate it. Some folks love the expressiveness
34 of dynamic languages, other people hate it. Some people ship successfully while strictly following Test Driven
35 Development,
36 others slap a few end-to-end tests on at the end of the project, and many people end up somewhere between these
37 extremes.
38
39 I've seen projects using all of these different approaches ship and maintain successful software.
40
41 So, again, my goal here is not to convince you that my way of coding is the only way, but rather to show you (
42 particularly
43 younger developers, who are prone to being intimidated by terms like "Clean Code") that you can have a successful
44 programming career using a lot of different approaches, and that mine is one of them.
45
46 ## TLDR
47
48 Three "dirty" coding practices I'm going to discuss in this essay are:
49
50 * (Some) big functions are good, actually
51 * Prefer integration tests to unit tests
52 * Keep your class/interface/concept count down
53
54 If you want to skip the rest of the essay, that's the takeaway.
55
56 ## I Like Big Functions
57
58 I think that large functions are fine. In fact, I think that *some* big functions are usually a *good* thing in a
59 codebase.
60
61 This is in contrast with Clean Code, which says:
62
63 > “The first rule of functions is that they should be small. The second rule of functions is that they should be
64 > smaller than that.” [Clean Code](https://www.goodreads.com/book/show/3735293-clean-code)
65
66 Now, it always depends on the type of work that I'm doing, of course, but I usually tend to organize my functions into
67 the
68 following:
69
70 * A few large "crux" functions, the real meat of the module. I set no bound on the Lines of Code (LOC) of these
71 functions,
72 although I start to feel a little bad when they get larger than maybe 200-300 LOC.
73 * A fair number of "support" functions, which tend to be in the 10-20 LOC range
74 * A fair number of "utility" functions, which tend to be in the 5-10 LOC range
75
76 As an example of a "crux" function, consider the [
77 `issueAjaxRequest()`](https://github.com/bigskysoftware/htmx/blob/7fc1d61b4fdbca486263eda79c3f31feb10af783/src/htmx.js#L4057)
78 in [htmx](https://htmx.org). This function is nearly 400 lines long!
79
80 Definitely not clean!
81
82 However, in this function there is a lot of context to keep around, and it lays out a series of specific steps that must
83 proceed in a fairly linear manner. There isn't any reuse to be found by splitting it up into other functions and I
84 think it would hurt the clarity (and also importantly for me, the debuggability) of the function if I did so.
85
86 ### Important Things Should Be Big
87
88 A big reason I like big functions is that I think that in software, all other things being equal, important things
89 should
90 be big, whereas unimportant things should be little.
91
92 Consider a visual representation of "Clean" code versus "Dirty" code:
93
94 <div style="padding: 1em">
95
96 <Image src={cleanVDirty} alt="clean vs dirty code visualization" />
97
98 </div>
99
100 When you split your functions into many equally sized, small implementations you end up smearing the important parts of
101 your
102 implementation around your module, even if they are expressed perfectly well in a larger function.
103
104 Everything ends up looking the same: a function signature definition, followed by an if statement or a for loop, maybe a
105 function
106 call or two, and a return.
107
108 If you allow your important "crux" functions to be larger it is easier to pick them out from the sea of functions, they
109 are obviously important: just look at them, they are big!
110
111 There are also fewer functions in general in all categories, since much of the code has been merged into larger
112 functions.
113 Fewer lines of code are dedicated to particular type signatures (which can change over time) and it easier to keep the
114 important and maybe even the medium-important function names and signatures in your head. You also tend to have fewer
115 LOC overall when you do this.
116
117 I prefer coming into a new "dirty" code module: I will be able to understand it more quickly and will remember the
118 important parts more easily.
119
120 ### Empirical Evidence
121
122 What about the empirical (dread word in software!) evidence for the ideal function size?
123
124 In [Chapter 7, Section 4](https://flylib.com/books/en/2.823.1.64/1/)
125 of [Code Complete](https://en.wikipedia.org/wiki/Code_Complete),
126 Steve McConnell lays out some evidence for and against longer functions. The results are mixed, but many
127 of the studies he cites show better errors-per-line metrics for *larger*, rather than smaller, functions.
128
129 There
130 are [newer studies](https://arxiv.org/pdf/2205.01842#:~:text=In%20this%20paper%20we%20examine,also%20decreases%20overall%20maintenance%20efforts)
131 as well that argue for smaller functions (< 24 LOC) but that focus on what they call "change-proneness". When it comes to
132 bugs, they say:
133
134 > Correlations between SLOC and bug-proneness (i.e., #BuggyCommits) are significantly lower than the four
135 > change-proneness indicators.
136
137 And, of course, longer functions have more code in them, so the correlation of bug-proneness _per line of code_ will be
138 even lower.
139
140 ### Real World Examples
141
142 How about some examples from real world, complex and successful software?
143
144 Consider the [
145 `sqlite3CodeRhsOfIn()`](https://github.com/sqlite/sqlite/blob/70989b6f5923a732b0caee881bd7c3ff8859e9c5/src/expr.c#L3502)
146 function in [SQLite](https://sqlite.com/), a popular open source database. It looks to be > 200LOC, and a walk around
147 the SQLite
148 codebase will furnish many other examples of large functions. SQLite is noted for being extremely high quality and
149 very well maintained.
150
151 Or consider the [
152 `ChromeContentRendererClient::RenderFrameCreated()`](https://github.com/chromium/chromium/blob/6fdb8fdff0ba83db148ff2f87105bc95e5a4ceec/chrome/renderer/chrome_content_renderer_client.cc#L591)
153 function in the [Google Chrome](https://www.google.com/chrome/index.html) Web Browser. Also looks to be over 200 LOC.
154 Again, poking around the codebase
155 will give you plenty of other long functions to look at. Chrome is solving one of the hardest problems in software:
156 being a good general purpose hypermedia client. And yet their code doesn't look very "clean" to me.
157
158 Next, consider the [
159 `kvstoreScan()`](https://github.com/redis/redis/blob/3fcddfb61f903d7112da186cba8b1c93a99dc87f/src/kvstore.c#L359)
160 function in [Redis](https://redis.io/). Smaller, on the order of 40LOC, but still far larger than Clean Code would
161 suggest. A quick scan through the Redis codebase will furnish many other "dirty" examples.
162
163 These are all C-based projects, so maybe the rule of small functions only applies to object-oriented languages, like
164 Java?
165
166 OK, take a look at the [
167 `update()`](https://github.com/JetBrains/intellij-community/blob/8c6cc1579ac358451ba2c5b8a54853249fdc5451/java/compiler/impl/src/com/intellij/compiler/actions/CompileAction.java#L60)
168 function in the `CompilerAction` class of [IntelliJ](https://www.jetbrains.com/idea/), which is roughly 90LOC. Again,
169 poking around their codebase will reveal many other large functions well over 50LOC.
170
171 SQLite, Chrome, Redis & IntelliJ...
172
173 These are important, complicated, successful & well maintained pieces of software, and yet
174 we can find large functions in all of them.
175
176 Now, I don't want to imply that any of the engineers on these projects agree with this essay in any way, but I think
177 that we have some fairly good evidence that longer functions are OK in software projects. It seems safe to say that
178 breaking up functions just to keep them small is not necessary. Of course you can consider doing so for other reasons
179 such as code reuse, but being small just for small's sake seems unnecessary.
180
181 ## I Prefer Integration Tests to Unit Tests
182
183 I am a huge fan of testing and highly recommend testing software as a key component of building maintainable systems.
184
185 htmx itself is only possible because we have a good [test suite](https://htmx.org/test) that helps us ensure
186 that the library stays stable as we work on it.
187
188 If you take a look at the [test suite](https://github.com/bigskysoftware/htmx/blob/master/test/core/ajax.js) one thing
189 you might notice is the relative lack of [Unit Tests](https://en.wikipedia.org/wiki/Unit_testing). We have very few
190 test that directly call functions on the htmx object. Instead, the tests are mostly
191 [Integration Tests](https://en.wikipedia.org/wiki/Integration_testing): they set up a particular DOM configuration
192 with some htmx attributes and then, for example, click a button and verify some things about the state of the DOM
193 afterward.
194
195 This is in contrast with Clean Code's recommendation of extensive _unit testing_, coupled with Test-First Development:
196
197 > **First Law** You may not write production code until you have written a failing unit test.
198 > **Second Law** You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
199 > **Third** Law You may not write more production code than is sufficient to pass the currently failing test.
200 >
201 > --[Clean Code](https://www.goodreads.com/book/show/3735293-clean-code)
202
203 I generally avoid doing this sort of thing, especially early on in projects. Early on you often have no
204 idea what the right abstractions for your domain are, and you need to try a few different approaches to figure out what
205 you are doing. If you adopt the test first approach you end up with a bunch of tests that are going to break as you
206 explore the problem space, trying to find the right abstractions.
207
208 Further, unit testing encourages the exhaustive testing of every single function you write, so you often end up having
209 more
210 tests that are tied to a particular implementation of things, rather than the high level API or conceptual ideas of the
211 module of code.
212
213 Of course, you can and should refactor your tests as you change things, but the reality is that a large and growing test
214 suite takes on its own mass and momentum in a project, especially as other engineers join, making changes more and more
215 difficult as they are added. You end up creating things like test helpers, mocks, etc. for your testing code.
216
217 All that code and complexity tends over time to lock you in to a particular implementation.
218
219 ### Dirty Testing
220
221 My preferred approach in many projects is to do some unit testing, but not a ton, early on in the project and wait
222 until the core APIs and concepts of a module have crystallized.
223
224 At that point I then test the API exhaustively with integrations tests.
225
226 In my experience, these integration tests are much more useful than unit tests, because they remain stable and useful
227 even as you change the implementation around. They aren't as tied to the current codebase, but rather express higher
228 level
229 invariants that survive refactors much more readily.
230
231 I have also found that once you have a few higher-level integration tests, you can then do Test-Driven development, but
232 at the higher level: you don't think about units of code, but rather the API you want to achieve, write the tests for
233 that
234 API and then implement it however you see fit.
235
236 So, I think you should hold off on committing to a large test suite until later in the project, and that test suite
237 should be done at a higher level than Test-First Development suggests.
238
239 Generally, if I can write a higher-level integration test
240 to demonstrate a bug or feature I will try to do so, with the hope that the higher-level test will have a longer shelf
241 life for the project.
242
243 ## I Prefer To Minimize Classes
244
245 A final coding strategy that I use is that I generally strive to minimize the number of classes/interfaces/concepts in
246 my projects.
247
248 Clean Code does not explicitly say that you should maximize the # of classes in your system, but many recommendations it
249 makes tend to lead to this outcome:
250
251 > * "Prefer Polymorphism to If/Else or Switch/Case"
252 > * "The first rule of classes is that they should be small. The second rule of classes is that they should be smaller
253 > than that."
254 > * "The Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to
255 > change."
256 > * "The first thing you might notice is that the program got a lot longer. It went from a little over one page to
257 > nearly three pages in length."
258
259 As with functions, I don't think classes should be particularly small, or that you should prefer polymorphism to a
260 simple (or even a long, janky) if/else statement, or that a given module or class should only have one reason to change.
261
262 And I think the last sentence here is a good hint why: you tend to end up with a lot more code which may be of little
263 real benefit to the system.
264
265 ### "God" Objects
266
267 You will often hear people criticise the idea of ["God objects"](https://en.wikipedia.org/wiki/God_object) and I
268 can of course understand where this criticism comes from: an incoherent class or module with a morass of unrelated
269 functions is obviously a bad thing.
270
271 However, I think that fear of "God objects" can tend to lead to an opposite problem: overly-decomposed software.
272
273 To balance out this fear, let's look at one of my favorite software packages,
274 [Active Record](https://guides.rubyonrails.org/active_record_basics.html).
275
276 Active Record provides a way for you to map ruby object to a database, it is what is called an
277 [Object/Relational Mapping](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) tool.
278
279 And it does a great job of that, in my opinion: it makes the easy stuff easy,
280 the medium stuff easy enough, and when push comes to shove you can kick out to raw SQL without much fuss.
281
282 (This is a great example of what I call ["layering"](https://grugbrain.dev/#grug-on-apis) an API.)
283
284 But that's not all the Active Record objects are good at: they also provide excellent functionality for building HTML
285 in the [view layer](https://guides.rubyonrails.org/action_view_overview.html) of Rails. They don't include *HTML
286 specific* functionality, but they do offer functionality
287 that is useful on the view side, such as providing an API to retrieve error messages, even at the field level.
288
289 When you are writing Ruby on Rails applications you simply pass your Active Record instances out to the view/templates.
290
291 Compare this with a more heavily factored implementation, where validation errors are handled as their own "concern".
292 Now you need to pass (or at least access) two different things in order to properly generate your HTML. It's not
293 uncommon in the Java community to adopt the [DTO](https://www.baeldung.com/java-dto-pattern) pattern and have another
294 set of objects entirely
295 distinct from the ORM layer that is passed out to the view.
296
297 I like the Active Record approach. It may not
298 be [separating concerns](https://en.wikipedia.org/wiki/Separation_of_concerns)
299 when looked at from a purist perspective, but *my* concern is often getting data from a database into an HTML document,
300 and Active Record does that job admirably without me needing to deal with a bunch of other objects along the way.
301
302 This helps me minimize the total number of objects I need to deal with in the system.
303
304 Will some functionality creep into a model that is maybe a bit "view" flavored?
305
306 Sure, but that's not the end of the world, and it reduces the number
307 of layers and concepts I have to deal with. Having one class that handles retrieving data from the database, holding
308 domain logic and serves as a vessel for presenting information to the view layer simplifies things tremendously for me.
309
310 ## Conclusion
311
312 I've given three examples of my codin' dirty approach:
313
314 * I think (some) big functions are good, actually
315 * I prefer integration tests to unit tests
316 * I like to keep my class/interface/concept count down
317
318 I'm presenting this, again, not to convince _you_ to code the way _I_ code, or to suggest that the way I code is "
319 optimal" in
320 any way.
321
322 Rather it is to give you, and especially you younger developers out there, a sense that you don't *have* to write code
323 the way that many thought leaders suggest in order to have a successful software career.
324
325 You shouldn't be intimidated if someone calls your code "dirty": lots of very successful software has been written that
326 way and, if you focus on the [core ideas](https://en.wikipedia.org/wiki/Algorithms_%2B_Data_Structures_%3D_Programs)
327 of [software engineering](https://www.web.stanford.edu/~ouster/cgi-bin/book.php), you will likely be successful
328 in spite of how "dirty" it is, and maybe even because of it!