We had our first programming lab proper today. Conditions and statements. Great fun. The aim of the exercise is to decide whether or not a given customer can see a movie at your multiplex. The inputs to the program are the age of the customer in years (age), and the number of the movie that the customer wants to see (filmNo). Movie number 1 is Looper (which is apparently quite a good film). In the UK you have to be at least 15 years old to see the film. Quite a few students wrote code like this, which makes very good sense:
if (filmchoice == 1 && age >=15) Console.WriteLine("Enjoy the film");
The condition will fire when the customer has chosen film 1 (Looper) and their age is greater than or equal to 15, which is just fine. However some folks then decided to improve the program to add the message that says “You are too young”. And they used the else keyword to achieve this:
if (filmchoice == 1 && age >=15) Console.WriteLine("Enjoy the film"); else Console.WriteLine("Access denied - you are too young");
This seems to make sense, but we now have a problem when we finish off the program. People start being denied access to films when they shouldn’t be. In fact they see lots of denied messages, which is very confusing.
The problem occurs because the program can enter the above statement in one of four states:
- Film is Looper and age is greater than or equal to 15
- Film is Looper and age is less than 15
- Film is not Looper and age is greater than or equal to 15
- Film is not Looper and age is less than 15
The if condition above will fire if the program is in the very first state (which is what we want if the customer can see Looper) but the else part will fire in all the other three states, leading to “Access denied” messages when we really don’t want them. One way to solve this is to split the program into two tests, so that the age test only takes place once the program has decided that the customer is seeing the Looper film.
Actually, there are lots of ways of addressing this issue. For me the interesting thing is that you need to be careful when you take a tiny piece of code that works fine (the original test) and then add a bit extra to it. Your program must handle all the input possibilities, not just the ones that constitute the “Happy Path”.