Magic Numbers

Line: Conditional Line
Easy Good Practice Learning Outcome Six Walkthrough
Type: Walkthrough
You should have completed: Driving Test This topic leads to: Ticket Sales

Summary

In the previous exercise, we used the number 17 directly in our code. This is sometimes referred to as a 'Magic Number', as it "appears" without explanation in the code. These numbers are problems for several reasons:

Task

  1. Open your Driving Test application
  2. Add a constant definition, before the line that says "static void Main"
  3. Notice the naming convention for constants, all capitals with words separated by underscores.
  4. Replace the magic number in the if statement with the name of this new constant.
  5. Run the program and enter '18'
  6. Run the program and enter '14'
  7. Run the program and enter '17'

Questions

  1. Now, how would you modify the program for Nigeria, where the legal driving age is 18?
  2. How would you create a constant for a string or a float value?

Notes

By placing the constant declaration where we did, within the class definition, it is available anywhere else within the class, a concept called scope that will be visited in more detail later. Constants are usually placed in this location and this also makes them easier to find if you need to change the value.