3 ms·
I wouldn't naturally think about summing lists in reverse so it becomes more cognitive effort to understand the code. I've seen plenty of termination condition
by duncanawoods 7y ago
I wouldn't naturally think about summing lists in reverse so it becomes more cognitive effort to understand the code. I've seen plenty of termination condition bugs on reverse iterations that might back that up.
A related thought is how modern code clean-up tools are doing things like reducing if-nesting e.g. turning this:
if (open)
{
stuff();
close();
}
into this, with early returns:
if (!open) return;
stuff();
close();
My feeling is that the first more naturally represents the idea I have of the behaviour and the second, like your reverse iteration, is an encoded version of that idea. I feel I have to make an extra cognitive step decode and reassemble it to create an idea of the behaviour.
I suspect the further you stray from the natural idea, the harder the code is to read, validate by eye and the more likely errors are to crop in. I'm don't know how subjective this is. I generally don't have a strong feeling about early returns it's just I have been noticing the slightly greater cognitive effort they are causing me compared to the logical chunking that nested-ifs provide.
- whoisthemachine 7y agoI personally find early returns to be easier to understand (I think of them as exit conditions) than nested if statements but to each their own.
- duncanawoods 7y agoThere are definitely cases like pre-conditions and validation that are natural early exists. There are other situations where it would sound really off and confusing to phrase instructions for a human that way. Not an easy task for an automatic code-clean-up tool to discern!
- usefulcat 7y agoIn the above example I tend to agree with you, but I'd definitely prefer early return over multiple levels of nested if statements unless all of the nested statements are quite small.