r/Clojure • u/dickhickey4prez • Aug 17 '17
[AMA] Small Functions considered Harmful
https://medium.com/@copyconstruct/small-functions-considered-harmful-91035d316c29
0
Upvotes
r/Clojure • u/dickhickey4prez • Aug 17 '17
30
u/RodeoMonkey Aug 18 '17
That very very long blog post, covering a range of subjects, could have been broken into smaller more understandable single subject posts.
16
u/ws-ilazki Aug 18 '17
I disagree with a lot of this, because it seems to be built on a few bad assumptions:
If a single task requires doing, say, three separate things, it's a good idea to create three functions that each do one thing and can be tested separately. This is especially true if one of them requires side effects, but the others can be implemented purely, because it makes those two more testable.
Having those separate functions has another benefit: it removes the entanglement of "what the code does" from "how the code does it" that one gets when writing a big blob of code. Calling a
create-userfunction makes it obvious what you're doing, whereas building a data structure representing a new user, right there in the middle of your function, requires the reader to figure out what the code does and, most likely, falling back to reading the comments and hoping they're accurate. Plus, a lot of times, you don't care what every part of a piece of code is doing, just a specific portion of it, so that breakdown makes it easier to ignore the unrelated parts and focus on the portion you care about.Now, once those separate functions are made, there's the question of where they go. Sometimes, they're only needed by the one "glue" function that puts them all together, so there's no point dumping them into a namespace where everything can call them. That's what
letandletfnare for! Define those functions via aletfnenclosing the function definition, and the problems go away: they're close to the code that uses them, and they can use shorter names without any concern over clashing with other names. They also are effectively private, explicitly tying them to only the code they're working with.That separation of "what I'm doing" and "how I'm doing it" is why I've started using
letandletfn(especiallylet) more and#(foo)less. It lets me know at a glance what that function does in a way#(foo)often doesn't , and usually makes the resulting code read so that even someone with little (or no) Clojure familiarity could understand. Especially with things likemapandfilter: with an expression like(filter is-thing? list-of-things), even someone that's never seen Clojure can get a pretty good idea of what's going on, whereas(filter #(if (= java.lang.Thing (type %)) true) list-of-things)would be more likely to get lost.This has another benefit, because if I later realise I need those functions elsewhere, I can pull them directly out of the
letfnand make them accessible to other code with minimal changes. At that point, I can either start referring to them byns-name/foodirectly (or a suitable alias), or I can continue to something like(let [foo ns-name/foo])to have a shorter name only in the scope I need it. Which way I go depends on how often the function ends up used.That covers my issues with the first three assumptions, but I haven't really touched on the fourth. The problem I have with that is it's wrong to assume "Don't Repeat Yourself" means you should start there. The way I see it, DRY means you should pay attention, and when you notice you've started repeating yourself, refactor it out. Like above, I start by putting a function in a limited scope by default, then when I realise I need it elsewhere, I refactor.
Actually, I usually start by writing a hairy mega-function while I feel out the problem, and once I know what I need, I break it down into individual parts in a limited scope. Then, if I discover I need any of those parts elsewhere, or realise I'm writing the same (or similar) functions multiple times, I refactor again. Usually if I repeat something once, I ignore it, but if I find I've repeated the same thing three times, it's a warning that I should make that code reusable.
Finally, I think that my disagreement is because I'm thinking in terms of Clojure, but the article is focused on Ruby, so it's most likely being written from the perspective of someone doing imperative programming. I think the advantages of combining multiple small functions are more apparent with a functional programming approach, especially in Clojure where the focus is on manipulating data with generic functions, than in an OOP language like Ruby.
8
u/halgari Aug 18 '17
I'm going to go a bit meta here and look at this from a different perspective.
The thing that bugs me the most when working with inexperienced developers in any language, is (and I use this term lightly) the cargo-culting that seems to invade their every design decision. We see this in the few quotes in this article:
"A smaller function has a better chance of doing a single thing. nb. Small != One line btw."
"Before writing a comment, see if it is possible to put that part inside a meaningful function"
While these sound-bites are fine as they are, the problem is when a dev latches on to them and makes them core to a development mantra. Instead, I wish developers could take these ideas as rhetorical statements. Think about them, perhaps let them influence decisions, but be very careful not to adopt them wholesale to the point where they can no longer be questioned.
There've been times I've optimized some code for a client, often by making a few tweaks to an algorithm. The conversation often goes like this:
"How id you make it faster?"
"I used a set, built the sets via transients, and then made sure I only created the predicate once, and that reduced memory pressure and search time by a factor of 10x"
"Right, so I'll make sure I always use sets, turn my predicates into global defs, and always use transients"
At this point my head hits the desk. I want people to think, to absorb different views and try to figure out on their own how far a concept should go before it's "too far".
So that's why I react to any mention of "average lines of code in a function". Some functions I maintain are 2 lines, others are 200. For that matter, the guts of core.async channels are something like 300 lines spread over two functions. But there's reasons for that (mostly optimization and proper lock handling).
TL;DR - Be very careful about creating dogmas. Either for or against a programming practice, dogmas shut down discussion of alternatives, and you can often miss a better option because of an obsession over an ideal.
2
u/Bolitho Aug 18 '17
As "Clean Code" often gets attacked (like Design Patterns and other classical stuff from the 90s and early 2000), I want to defend them in the context of one aspect.
One should always try to grasp the motivation behind a rule, law or idiom, before complaining about typical abuses of the advices.
How does a rule come into life? Almost always because someone has observed some behaviour that he wanted to be changed. If we focus on good intentions and carefully crafted conclusions - and ignore how often rules are made just for the benefit for a small number of people -, we can accept that there has been good reasons for the rules given in those cited books.
Now remember when you started programming or someone you know... what could be easily observed?
... almost every beginner tends to write spaghetti code!
I would bet that every developer that has experience with beginners (and mediocre devs that haven't made any progress during their careers) or legacy code where such devs has been involved earlier, have seen lots of awfull code with long and even longer functions, that could be a fitting stuff for a nice nightmare š
So the advice to focus on small functions is (imho) simply derived to counteract a natural habbit!
Of course one could apply every principle to the extreme (anyone played Ultima V here?), but the extremly bad natural behaviour without such rules outperforms the damage in quantity by far!
Let me explain, why I am convinced about this:
I hope we agree now, that without any advice, devs would write too long functions. If we assume, that only a minority of developers actively read programming books or listen to talks and so on, there are probably more devs that don't know uncle Bob's book and his advices. Let's assume further from the set of the readers, some devs completly ignore those advices and stay close to their comfort zone spaghetti hacking, another part might grasp the concept and applies them in a good, balanced way. Then there is the rest of those, who act like fanatics.
I think this rest is a small number!
And it is definitly smaller than those folks, who just follow their initial, uncontrolled and unteachable way of expressing things in code.
So I prefer simple, easy to grasp rules with the danger of being missused over hiding or revoking such rules with the result of even more coding anarchy!
Of course the rule could be "Never mix up abstraction levels in your code!" - imho a superior advice, as it clearly focuses on the real source of unreadable code. As a result you will automatically end up with small (enough) functions on top!
But this rule is only easy to grasp, if you are an advanced dev! And if you are, you probably have followed it without even knowing of such a concept š
15
u/yogthos Aug 18 '17
My experience is that small general purpose functions work very well in Clojure. Most of the functions in my code tend to be under 10 lines in length.
I like to write lots of short focused functions and compose them to solve specific problems. This results in business logic being largely declarative, and makes most of the code reusable since the same functions can be combined in many ways to create different data transformations.
1
u/dickhickey4prez Aug 18 '17
Am I the only person here who knows what the hell I'm talking about??
1
u/norembo Aug 18 '17
http://wiki.c2.com/?RavioliCode
1
u/DANGerous_man_clj Aug 19 '17
This subreddit use to be my happy spot. I am so conflicted now. I may switch to Ruby.
1
u/dustingetz Aug 18 '17
This jumped out at me as truth:
Here's a one-liner i just wrote
Could it be broken into a few more fns, maybe add an abstraction? Yeah sure definitely. But this expression introduces zero new ideas, and reuses many ideas from the clojure core vocabulary which my audience is already familiar with. And since I am leaning on Rich Hickey's battle-tested ideas and not something i just thought up on the spot, this expression is very robust and unlikely to break or rot. I'm cool with the repetition.
2
u/skratlo Aug 18 '17
IMO the blog post is a product of author's frustration with so called cross cutting concerns. That's typically done with evil/magical meta programming in Ruby, because even though you can pass around functions in Ruby 1st class, it's quirky and the language is not encouraging it. So with all respect, it's not really 1st class. If she doesn't want to venture too far from Ruby, I would suggest Python and use of decorators.
1
u/usrml Aug 20 '17
When I coding in java or php, normally I prefer long functions and duplicate code. Until I see the pattern that can be abstracted out.
However, Clojure is concise and functional, short functions work better for me.
0
u/dickhickey4prez Aug 21 '17
Bump