Falling Through and Landing on Values
I recently wrote a program that prompts the user to enter a month and a year then displays the
number of days in that month. It was a fairly simple concept to understand, and the program had
a variety of ways to be written. I wanted to find the cleanest way to write it so the code would
remain readable and concise.
My first thought was to use nested if statements to control the displayed information. It was good for input validation where I checked user input against a range of values. However, it would produce a lot of code if used in other parts of the program. For instance, if I want to create a condition for the month value 1, I need to tell the computer to display “January has 31 days”.
But what about values 3, or 5? With nested if statements, I have to write else-if statements for each of these instances. It’s too repetitive.
I could also expand the test conditions of the if statements, but it would reduce the readability of the code. Luckily, Java offers another selection statement known as a switch statement.
Similar to if statements, switch statements execute code based on the value of an expression or
variable. However, switch statements a feature known as “fall-through behavior”. With this,
I could write the code in a way that made it clear the number of days displayed would be the
same for months sharing the same numbers of days.
Nested if statements are great when dealing with numbers within ranges. Say January – June
had 31 days and the rest of the months had 30. An if statement could be written for the first
range, and an else statement for the rest. However, months of similar length pass in a non-consecutive
manner. (31, 28, 31, 30, 31…and so on) Therefore, I found it best to use switch statements to compare values in groups.
Fall-through behavior is a great way to deal with cases where there are multiple conditions that can be used to achieve a specific result. For this program where multiple months share the same number of days, switch statements are a great tool for the job.
Peaceful in action, never in mind
CodingFanatic