2 ms·
Personally, I like both for loops and higher-order functions over sequences. Loops can be more powerful, but they force the reader into an imperative mindset w
by munificent 11y ago
Personally, I like both for loops and higher-order functions over sequences.
Loops can be more powerful, but they force the reader into an imperative mindset where they have to mentally step through the code to understand what it's doing. That makes sense when the imperative model is the natural way to understand the code, but it can be overkill when there is always a simple high-level way to understand the operation.
Higher-order functions give you that. If I'm filtering a sequence "filter()" makes that fast and easy to read. But once I start chaining more than a few together, or start passing large lambdas to them, they lose that higher level reasoning and aren't worth it.
One way to look at it is, "How will the reader most easily think about this code?" If it's as a series of high-level transformations, use HOFs. If it's as imperative code, use a loop.
Another way is, "Does this code need to do control flow?" If so, use a statement. That's what they're good at. Otherwise, HOFs work fine.
I do find myself converting code from one form to another as it changes over time. I wish that transition cost was lower but I don't find it to be a big deal.