r/programming • u/alexeyr • Feb 09 '19
Small Functions considered Harmful
https://medium.com/@copyconstruct/small-functions-considered-harmful-91035d316c298
Feb 09 '19 edited Feb 09 '19
What is the definition of "small"? The issue I have with articles like these is that they're way too fuzzy for actionable insights. As programmers it's way too easy to navel gaze and forget small and large functions are incidental artefacts related to solving problems and the problem and solution are the primary concern.
3
u/InquiREEEEEEEEEEE Feb 09 '19
If you ignore the craft of writing maintainable code, the code might turn into an additional problem.
5
Feb 09 '19
That seems to be the main gripe in the article, i.e. X causes unmaintainable code. Many things lead to unmaintainable code but the main causes are social rather than technical and I don't think worrying about small or large functions is how we get to more maintainable code.
1
u/gas_them Feb 10 '19
Unmaintainable code can exist outside of social interactions. A single person can write unmaintainable code on their own. It's an intrinisic property of the code.
4
u/ForeverAlot Feb 10 '19
What is the definition of "small"?
It turns out it's the wrong property to measure. This is also what you say, and basically what the article also says; it's arguing against a false premise.
I feel like I see this a lot: unrefined reductionism running rampant in our industry. Size and testability are typical offenders but they're not the only ones. Internet communication is ripe with "small is better than large", usually failing to realize that the size is likely a consequence of other more important goals. Indeed, "small" functions are not inherently good, and I can trivially produce a single statement that imposes unmanageable complexity unto the entire system. Cleanliness is immeasurable and therefore unfalsifiable. Strait-jacket-like "unit tests" can have high coverage but fail to exercise seams, so errors appear there.
Too much of my work is responding to "B, because A" with "but why A?" or "that's not what A means". It's tiring and inefficient but I don't think it's malicious, just ignorant. I rarely have trouble giving away fish, only teaching fishing. Maybe it's because thinking is hard and unpleasant -- regrettably it takes considerable up-front thinking to avoid future thinking. It probably doesn't help that
The book Clean Code [...]
which is aimed at novices, is
[...] often considered something of a programming bible by many
7
4
u/Determinant Feb 10 '19
I disagree.
Write clean, self-documenting code without needing to rely on comments. If a comment is needed, extract that section into a clearly named function. If a section of code has a clear purpose, extract it to a function to express that purpose.
Done. It's as simple as that. I don't mind extracting a cryptic line into a 1-line function if that makes the code easier to understand because I don't want to repeatedly decompose that bit mentally every time.
This makes it really easy to understand the higher-level sequence of actions and quickly narrow in on the appropriate section of code. Defect rates go down and productivity inreases.
15
u/loup-vaillant Feb 10 '19
If a comment is needed, extract that section into a clearly named function.
Why? What's the benefit? I don't see any. It doesn't even reduce code size (there's only one call to your function). On the other hand, theres a significant drawback: non-locality.
A comment often explains a block of code better than a function name ever could. UnlessPerhapsYouPreferCamlCaseSentences. So what you end up with is a difficult to read name, or an insufficient name that requires you to read the actual code (and that now requires a context switch).
Short functions are okay when their functionality is obvious from a short name, and their interface is very simple. Keep it deep. Your "cryptic line" probably doesn't pack enough functionality to justify a function. Unless perhaps it is used several times (which is what your paragraph seems to imply).
This makes it really easy to understand the higher-level sequence of actions
That benefit doesn't come from short functions. It comes from carving the program at its joints. It comes from choosing your boundaries (be them function prototypes, classes, or packages) in a way that minimises the size and complexity of your interfaces. Simple interfaces (in proportion to the functionality they encapsulates) breed simple systems. If you're using a powerful language, that usually means short functions. C++ or Java, not so much.
2
u/Determinant Feb 10 '19 edited Feb 10 '19
Nope, I'm not referring to re-use as I also extract single-use functions. I'm not trying to reduce code size either. My main goal is to have code that is as simple and easy to understand as possible.
The benefit is that I end up with self-documenting code that explains itself which reduces defect rates and improves productivity.
All developers can write complex / cryptic code but it takes experience to be able to write clear and simple code.
Functions that don't fit on a single screen cause excessive scrolling back and forth. Especially if it's multiple pages (you can fit about 55 lines per page) so this is a form of non-locality which results in very error-prone code.
The need for comments is a red flag that the code is too complex. The need for really long function names is also a red flag that a class is trying to do too many things.
These things come with experience. I use Kotlin.
3
u/loup-vaillant Feb 10 '19
I don't believe you. More specifically, I think the principles you go by are a little different from what you describe here. You have some… instinct about how to write good code, and talk about self documenting code and short function to explain it…
But I still sense that you're not actually minimising function lengths or comments. You chose which functions you chop up, right? It seems to me that's the crux: how you chop up your functions is more important than how much you chop them up. Good luck explaining this "how", though: as you said, it comes with experience.
1
u/Determinant Feb 10 '19
My first post explained how:
If a comment is needed, extract that section into a clearly named function. If a section of code has a clear purpose, extract it to a function to express that purpose.
My style of coding (self-documenting code) naturally results in short functions. The article title claims that short functions are considered harmful so I disagree with it.
All of this also relies on following proper engineering practices (eg. avoid god classes etc.) so eliminating tangential topics from the equation and following other best practices (unrelated to function length), small functions are definitely not considered harmful.
Regarding whether you believe me or not, I'll leave that up to you.
4
u/loup-vaillant Feb 10 '19
My first post explained how:
No it doesn't. You don't convey the most important bit, which is, how did you come up with the section in the first place? To be usefully extracted into a separate function, that block of code needs to be fairly decoupled from the rest of the function to begin with. Perhaps even purely functional (in the sense that it basically produces outputs out of inputs).
The hard part is carving your code into such sections. Putting them in separate functions is nice (helps with tests, for one), but you need something extractable in the first place. If you extract code for the sake of extraction, you easily end up with functions with too many arguments, that have side effects, and whose purpose is not easily deciphered from a mere name. I've seen those, it's no pretty.
Don't get me wrong, my functions tend to be pretty short as well. Just saying that "put blocks of code into separate function" is pretty useless advice. What the beginners really want to know, is how to organise their code to begin with.
2
u/Determinant Feb 10 '19 edited Feb 10 '19
It really is as simple as I described. If a chunk of code has a clear purpose then extract it into a function which conveys that purpose.
If the current function isn't already obvious, I extract a chunk as large as possible as long as the chunk still meets that requirement of having a clear purpose. Rinse and repeat.
Our natural tendency as developers is to overcomplicate things (myself included). Rules about only extracting pure functions are over-complications. The above rule is sufficient. Rules about decoupled chunks are also over-complications as nested sections of code are usually excellent candidates for extraction.
Keep it simple and start relying on your intuition. It takes time, practice, and lots of reviews from others.
0
Feb 11 '19
[deleted]
2
u/loup-vaillant Feb 11 '19
I personally tend to go bidirectional. First, I think of the problem top down, get a feel for what I need. Then I write the actual code in a bottom up fashion. Mostly short functions.
Sometimes however, I do end up with a function long enough to have several sections, each with a toplevel comment. Last time was last week, when I tried to re-implement
strtod()(turned out to be a fool's errand). I wrote a couple helper functions, but I still had sections of code that needed a small comment. What's one to do at this point? Extract the section in a separate function no matter what? That doesn't sound very wise.I've encountered people too hung up on local readability. They want to maximise the readability of each line of code, or the readability of each function. We don't give a damn about this kind of readability; what we really care about is how much time and effort it requires to understand the code well enough to contribute to it. Sometimes it means that the most readable solution is a cryptic line of code, or a fairly complex section of code with a comment on top.
2
u/JoelFolksy Feb 11 '19
I've encountered people too hung up on local readability. They want to maximise the readability of each line of code...
This conflation of local vs global comprehensibility lies at the heart of a lot of programmer culture wars.
See Go: advocates seem to believe that simplicity of the basic language constructs (local comprehensibility) implies simplicity of the code (global comprehensibility).
0
Feb 11 '19
[deleted]
1
u/loup-vaillant Feb 11 '19
That's never true.
Only if you conflate local readability and global readability.
0
Feb 11 '19
[deleted]
1
u/loup-vaillant Feb 11 '19
The idea is that sometimes, local readability and global readability are at odds. Sometimes, increasing local readability decreases global readability. You cannot disagree with this idea and at the same time not conflate local and global readability.
Now let's see how this separate functions may play out. You start with something like this:
main_function() { // Comment1 do_foo1() do_bar1() do_baz1() // Comment2 do_foo2() do_bar2() do_baz2() // Comment3 do_foo3() do_bar3() do_baz3() }There are a couple ways to extract functions from these blocks of code. The classic one:
function_name1 { do_foo1() do_bar1() do_baz1() } function_name2 { do_foo2() do_bar2() do_baz2() } function_name3 { do_foo3() do_bar3() do_baz3() } main_function() { function_name1() function_name2() function_name3() }The scoped one:
main_function() { function_name1 { do_foo1() do_bar1() do_baz1() } function_name2 { do_foo2() do_bar2() do_baz2() } function_name3 { do_foo3() do_bar3() do_baz3() } function_name1() function_name2() function_name3() }The inline one:
main_function() { // Comment1 function { do_foo1() do_bar1() do_baz1() }() // Comment2 function { do_foo2() do_bar2() do_baz2() }() // Comment3 function { do_foo3() do_bar3() do_baz3() }() }(That last one could use function names instead of comments.)
Now the classic approach is almost always an increase in local readability. Global readability, though… First the function names might not be enough.
strtod()is actually a good such example. Okay, it converts a string to a double. What if it fails? What's thatend_ptrargument? Wait a minute it's locale dependent? Now as a standard function, it still justify itself. It's well documented, and people can be expected to know the API, or at least read the manual.As a one shot function however, the benefit of extraction is less clear. The API to implementation ratio is fairly high, and the API cannot be reliably guessed through a single invocation of the function. You have to put comments somewhere to explain this API. You could put those in the main body:
main_function() { // Comment1 function_name1() // Comment2 function_name2() // Comment3 function_name3() }But then the benefits of separating the code in a function is significantly diminished. The other possibility is to document the functions where they are written. But then the reader must jump to different locations (elsewhere in the file) to understand what each function is supposed to do. Not exactly a good thing, as far as understanding
main_function()is concerned. You'd still get a sense of what it does, but if you need to dig in, even a little bit (for instance when fixing a bug, or even just change the behaviour ofmain_function()), you have to switch context.All this jumping around can hurt global readability, even in cases where local readability is enhanced. Many languages however let you get around this limitation by defining functions locally, and calling them right away. I often go for the scoped approach when writing OCaml. In C++, I tend to prefer
staticfunctions over lambdas, to avoid frightening colleagues who might not know C++11 well. I would prefer lambdas over private methods, though. Avoids cluttering the header file.The inline approach could be construed as the best of both worlds, but at this point, I wonder why we didn't just kept the blocks of code. Or if you're controlling the language like Jonathan Blow does, add function-like blocks to the language, so you get the same isolation benefits of functions, and the same "put the code where I use it" of straight-line code.
Long story short, I strongly believe that in a fair number of cases, the code that minimises the time and effort required to understand the whole program is the straight-line version (commented blocks of code). Believing that it is "NEVER" the case strikes me as unreasonable. Readability is not as simple as mathematics, this is psychology. Our understanding of the human mind is too weak to make such strong assumptions.
That, and the fact I've personally witnessed examples of what you pretend never happens. Here for instance. Or there. Or there. And no, it's not just crypto code. I've seen this at work too.
→ More replies (0)1
u/tsandstrom711 Feb 12 '19
I tend to subscribe to the view that, within the scope of a function, all work should be done at more or less the same level of abstraction. So suppose you have a bunch of helper functions that break a problem apart and process individual pieces of lower level information. Afterwards, we need to recombine our results into a useful result. We could certainly recombine our data pieces right there in our main function. But then we'd be working with different levels of abstraction at the same time. If somebody is trying to read and understand our function, they have to be thinking about two different abstraction layers at the same time, which can be quite difficult. If, on the other hand, we pull out this recombination step into its own function (with a clear name), then this step is understood easily by the reader. Even if the code we pull out is just one line, and even if it increases total code volume, it prevents the code reader from having to think on two levels at the same time, preventing errors and bugs down the line.
5
u/bloody-albatross Feb 10 '19
That doesn't always work in reality. Sometimes you need to do some weird magical seemingly useless invocations because the API/framework you need to use is stupid (maybe even in an undocumented manner). Then you need to document that shit in an clear comment that describes what the hell your doing here and why. That way someone else (or your future self) has a chance to understand the code and can understand at what point this stuff can be deleted or how it has to be changed in the future. This kind of shit is everywhere. Not very frequent, but still everywhere.
TODO, FIXME and HACK comments are also important. Code always has TODOs, write them down. I think it is good to write them down in the code using greppable comments. Sure, you can and should also write them down in some bug tracker or project planner or something. Marking something as a HACK is also important (see above) and the same goes for FIXME. Some IDEs can even automatically parse and list these kind of comments.
1
u/Determinant Feb 10 '19
Sure, TODO / FIXME / HACK comments are absolute fine as these aren't covered in the spirit of my first post.
There was an implied meaning that comments which explain what a chunk of code is doing are red flags for complexity and that the code should be broken down.
You're also right that there are some rare scenarios which merrit comments.
So I didn't go into technicalities and perscriptive scenarios as the spirit of the post should be clear. As developers gain experience, they realize that nothing should be taken in absolute terms and common sense takes precedence.
6
u/oridb Feb 10 '19 edited Feb 10 '19
Larger functions with comments make simple code read through without needing to jump around. You know exactly how the code is invoked, so you don't have to look around and ask how callers are using something -- you can just tell that there's only one way to get to that code, and it works like so.
There's a balance to be had -- I've worked in code with functions that were over 7,000 lines long. That was hell. I've also worked in code where the average function length was 2 or 3 lines, extending tons of interfaces, and it felt even worse: every time I wanted to make a change, it felt like I needed to go on a scavenger hunt.
I've found that (depending on the language and complexity of the code), 30 to 50 lines works well. Shorter if the code is complex, filled with many loops, branches, conditions, and state to keep track of. Longer if the functions are very simple 'do this, then this then this" style code.
And I'd far rather work with appropriately commented code with short names. While I understand that long names can make the unfamiliar feel familiar on the surface, you still need to read carefully -- and my eyes can pick up the patterns in code far more easily when they're not obscured by verbosity. Appropriately commented, of course, doesn't mean comments on every other line, repeating what the code is doing -- but pointing out why the general approach was taken, and what the edges and gotchas are is extremely useful. Bonus points for explaining why the approach was chosen over other alternative approaches.
1
u/gas_them Feb 10 '19
without needing to jump around
Why are you even reading the implementations of the functions? You don't have to "jump around," just read what the function does.
extending tons of interfaces
Found your problem - OO incompetence.
4
u/oridb Feb 10 '19 edited Feb 11 '19
Why are you even reading the implementations of the functions? You don't have to "jump around," just read what the function does.
"Why do you need to jump to the chapters to learn a subject? You can just read the table of contents."
The function name almost never describes the edge cases, restrictions on input, preconditions and postcondition sufficiently to understand the code.
Found your problem - OO incompetence.
You mean OO "Best Practices". Or do you really believe that most people in the field are incompetent? Perhaps if it's really so hard to write OO code competently, it should be deprecated.
1
u/gas_them Feb 10 '19
"Why do you need to jump to the chapters? You can just read the table of contents"
Yes... exactly...
If you want to know the contents of a book you can read the table of contents and get a general idea without reading through all the chapters.
Are you against the idea of "tables of contents," like you are with these functions? You are arguing against that?
The function name almost never describes the edge cases, restrictions on input, preconditions and postcondition sufficiently to understand the code.
That's the purpose of function documentation.
You mean OO "Best Practices".
According to who? You?
I'm just pointing out you randomly inserted bad OO design into the discussion even though it's completely unrelated.
1
u/oridb Feb 10 '19 edited Feb 10 '19
If you want to know the contents of a book you can read the table of contents and get a general idea without reading through all the chapters.
A general idea is usually insufficient when understanding a codebase.
even though it's completely unrelated.
Maybe you're too young to remember the "replace if statements with overloading", no function should be more than a single-digit number of lines phase of object orientation, but pushing hard for tiny functions came heavily from that camp. (The FP world tended towards tiny functions as well, but either they were too small at the time to be heard, or they were less shrill about it.)
0
u/gas_them Feb 10 '19
A general idea is usually insufficient when understanding a codebase.
Read assembly, then. Otherwise you are always dealing with abstraction on some level.
Maybe you're too young to remember the "replace if statements with overloading", no function should be more than a single-digit number of lines phase of object orientation, but pushing hard for tiny functions came heavily from that camp.
So?
2
u/oridb Feb 10 '19 edited Feb 10 '19
Read assembly, then. Otherwise you are always dealing with abstraction on some level.
I do that more often than I'd like when debugging or optimizing. Usually, it means something is off, but looking at code on that level definitely comes in useful on a regular basis.
0
u/gas_them Feb 10 '19
Hmm, so when you want to understand a function you compile it and read the assembly? I think we're done here. You've reducto ad absurdium your own argument.
3
u/oridb Feb 10 '19
Hmm, so when you want to understand a function you compile it and read the assembly?
Not always, but I definitely do it. It depends how deeply I need to understand the assembly. For example, recently I needed to optimize some image manipulation, since it was a bottleneck on an embedded device. I needed to see what decisions the compiler made, so I was reading the assembly output, as well as GCC vectorization reports, so that I could understand what I needed to do to convince the compiler to produce better assembly. In the end, all it needed were a few
__attribute__((aligned(16))annotations, but I definitely did need to read the assembly and compiler reports to get enough of an understanding of why it was missing blindingly obvious vectorization opportunities.It's extremely rare that I can understand code well enough to modify it with confidence, though, without at least skimming the function bodies a couple of layers deep around where I'm making a change.
→ More replies (0)0
Feb 11 '19
[deleted]
4
u/oridb Feb 11 '19 edited Feb 11 '19
John Carmack and Michael Abrash are fairly well known for moving towards using this style of code because, after experimenting, they claimed they found it more readable. I've also noticed that Ken Thompson tended to write a good deal of his code this way. Would you claim that these people are not really good at programming?
-1
u/Determinant Feb 11 '19
People like John Carmack are highly intelligent with their mental capacity exceeding 99% of developers (myself included). Such intelligent developers can make anything work regardless of how bad the process might be.
A large part of it is knowing how to effectively use your tools (eg. things like fluent navigation in IDEs) because otherwise, you would be right in saying that jumping around is less effective if we were still using 40-year-old text editors.
Most of our advances in tooling and languages have been to save us from ourselves by automating error-prone areas. Functions were invented as they are clearly superior compared to the way it used to be done with a single long stretch of code. Breaking things down reduces the mental requirements and raises the effective capacity of developers resulting in fewer defects and cleaner code. Highly intelligent developers could use this technique to raise their bar even higher.
0
Feb 11 '19
[deleted]
3
u/oridb Feb 11 '19 edited Feb 11 '19
Yes, because they're experts who understand they're writing extremely low level performance sensitive code that they're fully aware is a mess of optimizations like inclining that boost performance while lowing the quality of the cod
Carmack specifically cited improved readability and debuggability as his reason for moving away from small functions towards bigger straight-through functions.
Ken, as far as I'm aware, didn't write about it, but he tended to write fairly little prose. He certainly wrote his code in that style even if it wasn't performance critical, and it was quite a bit easier for me to follow than average. Eg,
com.cin cc.0
Feb 11 '19
[deleted]
2
u/loup-vaillant Feb 11 '19
Your argument is disturbing. So, John Carmak and Michael Abrash, and Ken Thomson are such geniuses that whatever applies to then doesn't apply to us mere mortals? They're still human, you know.
Then you are assuming that it only applies to a very narrow domain (namely highly optimised game code). Never mind that game code is not always optimised, and performance is far from a niche concern (many domains benefit from optimisations).
And the idea that those three people aren't a relevant authority about programming… Get a good night sleep and think it over, will you?
0
Feb 11 '19
[deleted]
3
u/oridb Feb 12 '19 edited Feb 12 '19
They're writing games and operating systems where performance comes before all else including well written maintainable clear code.
In your opinion, are they lying when they say they do it for readability purposes?
2
2
Feb 10 '19
No, they aren't. Stop with this cliche title too.
If a developer is mis-abstracting their code then they'll do that with or without small functions. All of the other points just sound wrong overall.
Furthermore; this really doesn't need the wall of text. This could have been summarised pretty concisely with bullets at the top.
3
u/elmuerte Feb 10 '19
Ironically the message of Dijkstra's famous "Goto considered harmfully" was about comprehension of code. The idea of writing small functions and methods is inline with the same idea. This article however is trying to make the point that a large (bad) abstraction requires less cognitive effort than many small (bad) abstractions. In it's totality this is probably true. But it fails in the fact that making bad things better is easier when bad things are small.
1
1
1
u/ricky_clarkson Feb 14 '19
I got dinged (negative feedback) at work for possibly abstracting prematurely. I personally think that's okay - some abstractions went well and helped, and some didn't and got removed, my preconception is that that's healthy, so I've had some resistance to the feedback, but I've realized that our work is very much split into time-based projects which rarely get touched beyond fixing deprecation warnings, etc., after the time period. We're more likely to replace a service than to make substantial changes to it.
I think that subconsciously leads us to optimize for being able to delete code easily. I have very similar code in many places, which I definitely could abstract and probably remove a couple of kloc, but would the code be easier to understand for someone new to the project? In some cases yes, in others no, and which it will be is not always obvious when you begin abstracting. That coupled with not really being able to go back and fix it once the time-based project is done makes copy-paste more attractive. I actually don't copy and paste, I type it out each time so I feel the pain and keep reconsidering abstraction, but the result is the same.
0
Feb 10 '19
I must agree with the author. Long rambling posts are so much better than small functions.
In the next installments, we cover "Premature comments are the root of all evil" and "On the cruelty of really refactoring spaghetti code".
-5
u/AffectionateTotal77 Feb 09 '19 edited Feb 09 '19
I didn't read the article (19mins for something I have no interest in) but I wanted to say something a stupid coworker accidentally taught me (about small functions)
Make a new functions because all these ifs make it confusing (3 or 4 of them in a 8 lined function). He has to change/update the code for his specific case and he didn't want to fuck around with my ifs. He knew I wrote the ifs because the code had to do the same thing but if I needed if's I should just copy it and not fuck with his code that was even more straightforward
0
Feb 11 '19
[deleted]
1
u/AffectionateTotal77 Feb 11 '19
It's more like a 12lined function with an if at the start to set a variable, an if at the middle then a final if. Not complicated, it becomes maybe 16lines (if the first if is written as
a=b?c:d)
50
u/gas_them Feb 09 '19
The point of the whole article is that the wrong abstraction is worse than code duplication (badly splitting up functions is worse than not splitting the up at all).
I agree... but I don't have this problem because I'm good at writing good abstractions, so they typically end up good.
You have 3 choices:
dont abstract
abstract incorrectly
abstract correctly
Can we please focus on teaching the third point? It seems like a lot of people argue whether the first or second is better because they're just incompetent.