Constant definitions in a program

Thursday, May 6, 2021
Design Java BSL

In our program, we want to avoid the so called magic numbers - constants appearing in expressions. We do this by introducing constant definitions. Let's say we have a program to convert time in hours, minutes and seconds to total number of seconds. Without using constant definitions, we could write such a program like:

(define (time-in-seconds hour minute second)
    (+ (* 3600 hour) 
       (* 60 minute) 

Later when we are reading such a program, it takes some mental energy to decipher what 60 and 3600 stand for. Constant definitions help us design better programs by avoiding two problems:

  1. We give names to constants so they are easy to read and comprehend.
  2. If that constant is used more than once in a program, we only have to change it in one place - where it is defined. So the design rule to follow is:

So with this rule, let's rewrite our earlier program:

;; constants
(define SECONDS-PER-HOUR 3600)

;; functions
(define (time-in-seconds hour minute second)
    (+ (* SECONDS-PER-HOUR hour) 
       (* SECONDS-PER-MINUTE minute) 

Naming constants in all capitals is also another ‘visual’ cue that these should not change in the program.

It's worth noting that there may be different ways to enforce a variable to be ‘constant’ in a given language. For example, in Java, we have to use final keyword for such variables.

public class Time {
    public static void main(String[] args) {
        // constants
        final int SECONDS_PER_HOUR = 3600;
        final int SECONDS_PER_MINUTE = 60;

        // variables
        int second = 30;
        int minute = 30;
        int hour = 20;

        int timeSeconds = SECONDS_PER_HOUR * hour +
            SECONDS_PER_MINUTE * minute +

        System.out.print("Total seconds: ");