Yesterday I posted some very simple sample code. I have to admit that I spent a lot of time on some of the details but may not have spent enough on some of the other details. This is always an issue when working on sample code for demonstrating a specific, often detailed concept. This is also an issue with code for tests and quizzes BTW. I remember one of my APCS students complaining that the APCS test was all about showing bad coding examples. A bit harsh perhaps but when writing code for a test one is very constrained by space. The good news is that these examples can lead to having some great conversations with students. For example, in the case of yesterday’s code samples I received email from a teacher friend of mine calling me out. Sort of.
Should you teach students to break out of loops or to use a better loop to meet the need? In your programs today(?) you use a for loop to go through the elements until the end, but if you find a bad value break out. Shouldn’t you have used a do while loop? That way you place clear conditions for when to stop looping?
One example of the code in question is this C# example.
In that code I use a break statement to exit the loop early. Standard structured programming, as I learned in college many years ago, says that is bad. The “rule” is that a loop should have one and only one exit point. When you add more exit points you add the potential for problems with people understanding the code, maintenance issues, and unexpected consequences when programs are extended or modified in the future.
A more strictly by the rules structured programming code might me something like:
That’s probably still not the best way but it at least demonstrates the principle of one exit for the loop. This brings up the point I was making earlier about simple samples being more difficult than it may seem. The first example shows the comparison pretty clearly in a simple if statement. The second example shows the same thing but the Boolean expression in the while is more complicated then the one in if statement. Also in the second example the loop “feels” kind of forced to me. Of course often times in a real program there would be other things going on inside a loop that we are using. In a more complex “real” program the value of using the while loop might actually be more obvious.
We could write a very complicated example that would demonstrate several concepts or features of course. The problem there is both one of focus and potentially too much complexity making it hard for beginners to understand the code. Often then we are faced with the real trade off between great code all up and simple easy to understand samples that may not be ideal code.
When these examples sparks conversation in or outside of class be sure to take advantage of these as real learning opportunities. You can always pretend you did it on purpose.