Posts

Showing posts from April, 2014

#6. Ensure entry and exit conditions in loops

There are at least two questions you should always ask yourself while you're writing code for a loop - and ask yourself again after writing it. Here they are: Will the loop body be entered at least once? Will the loop ever be exited? If your loop is a do .. while , the first question has an obvious answer: yes. It will be entered at least once (as long as the execution point reaches it, of course). That's why you chose that structure in the first place. If it is a while or a for , you should pay more attention to that. Review the loop condition thoroughly and think about the possibility of it being false at the very beginning of the loop. In that case, the loop body would not be executed. Is that scenario correct your design, or is it something to avoid? If the latter is true, then you should write the specific code to handle that. About the second question, the loop will be exited whenever its condition is evaluated to false . The condition is evaluated once for each it