4 ms·
The problem I have with loops is that they are like fly-paper. Once you have a loop iterating over a collection it's tempting to add more and more to it, mixing
by michaelfeathers 11y ago
The problem I have with loops is that they are like fly-paper. Once you have a loop iterating over a collection it's tempting to add more and more to it, mixing responsibilities in run-on code. This isn't theoretical, I see code like this all of the time. It's nearly impossible to abuse HOFs that way.
- cousin_it 11y agoYeah, I agree. "Fly-paper" sounds a bit judgmental though. For a more neutral metaphor, we could say that HOFs are like Lego bricks, and loops are like clay. Both have their benefits and drawbacks. I've been fascinated by HOFs for many years, but my personal projects are filled with "loop abuse" and mixed responsibilities, all soft and malleable, just the way I like it. If I had to dismantle half the thing just to change the color of one brick, I'd give up pretty quickly.
- michaelfeathers 11y agoThat sort of change is easy - at least you have bricks. Clay just oozes all over itself. Whatever works for you. If it's just your code, you have enough control to keep loops from going bad. Large multi-programmer projects seem far more prone to that problem.
- agumonkey 11y agoI second gp comment. HOF and FP in general constraints programming so much it leads to decoupled logic. Sometimes too much, but it's a good way to balance imperative statements allowing too much state.
- reagency 11y agoFlypaper accumulates more bugs than clay.
- s_kilk 11y agoYeah, I see this all the time. Giant 600 line functions made of nested for loops, with all sorts of shit going on at each layer. The author will insist it's basically impossible to abstract any of it, that the for-loops are the only way to capture the essence of the problem. Then you spend two days tracking down a bug in there and discover that it's all actually some combination of map, reduce and a fold with a closure at heart.
- visarga 11y agoMaybe the solution is to break the large function into several smaller ones, even if they still make use of for loops.
- michaelfeathers 11y agoNo doubt. But once it gets to a certain point the costs of doing that are much larger than having started in a compositional style. If you have Martin Fowler's Refactoring book, check out the intro example. It's a 20 line function and the amount of refactoring work he does on it to make it sensible is quite large.