[ Editor's note: I wrote this because I forgot, again :-( ]
Unbounded loops are bad. If there is a bounded loop that can be used instead, use that instead.
Code really has two major flow-of-control constructs. One is conditional execution. You execute the code “sometimes”. We see that as ‘if’ statements, but there are all sorts of variations on that theme.
The other is loops. Loops come in two flavours, bounded and unbounded. A bounded loop is one that has the number of iterations effectively set in advance. A good example is a ‘for’ statement, with a variable called ‘i’. It starts at 0 and finishes at some ‘size’. The 0..size is the bounds for that loop. It will “always” stay within them.
Sometimes we don’t have bounds. A REPL is a good example. As long as the user keeps typing in text, the loop will continue to run. At some point, the user types in something special that triggers the code to ‘break’ the loop. Could be ‘exit’ or ‘quit’ or ‘EOF’ or something. It could just be a dynamic terminal triggered by the end of work. There are plenty of other places, like communication protocols, where there are often unbounded loops. But all of them are special.
Sometimes, people encode their loops as unbounded, even though they are essentially bounded. If encoding it as a bounded loop is only slightly less convenient, then it should be encoded as a bounded loop. Being clever with loops is really bad.
The reason for this is that it is self-describing. If you hit an unbounded loop, you might have to search around through a whack load of spaghetti to find its bounds. That’s a huge waste of time.
Another good reason is computational complexity. If you are coding loops, you really, really, really need to know how long they are going to take. If it loops on 3 or 4 things, you can quickly ignore it, but if it might loop on a million things, you can’t just chuck code like that out into production and hope for the best. One day it will fail, and people will be angry about it. If it can loop ‘that hard,’ then at bare minimum you’ll need some sort of testing to be in place so that you have the certainty that it won’t be you causing a denial of service attack on the system.
So, if you quickly read the code, and you can instantaneously pick up all of the bounds, then often in your head you can have a reasonable degree of certainty that when this code gets out there in the world, its behaviour will not sufficiently degrade from the behaviour you’ve been seeing while you worked on it in development.
That certainty is everything.
You have become an expert in programming because the code you write does only and exactly what it should do relative to your expectations. Obviously, that doesn’t mean it is “right”; it just means that when it runs, you will not be surprised, and you really don’t want surprises, do you?
No comments:
Post a Comment
Thanks for the Feedback!