3 ms·
One other heuristic I follow that's not mentioned in the essay is: If one branch of an "if" statement is much shorter than the other, change the condition so th
by jcl 18y ago
One other heuristic I follow that's not mentioned in the essay is: If one branch of an "if" statement is much shorter than the other, change the condition so that you can put the short branch first.
My reasoning is also involves memory: While the reader is reading the first branch, he needs to hold the possibility of an "else" branch in his head, along with the condition. By minimizing the length of the first branch, you minimize the amount of time he needs to remember this.
- scott_s 18y agoI disagree. I think it depends on context. Generally, one branch is the more common case, and I prefer to put that one first. It's the main flow of the code.
- queensnake 18y agoYes but, say you've got a longish chunk of code with several error conditions; you come across an 'else' after a lot of closing braces. What the heck does it match with? What other error conditions need handling and got forgotten in the forward rush of common cases? Error handling is easy to forget; the common case remembers /itself/ you might say, and can be put off for a moment while you get the clutter out of the way. My MO, anyway.
- scott_s 18y agoI stress the common case for the same reason that when I construct sentences, I try to put the main point up front, and save the side comments for later. Example: "I ran into Bob while walking to the store." "While walking to the store, I ran into Bob." The point I'm trying to get across, in this case, is that I ran into Bob. I try to do the same with code.