Definition Of Constants And Magic Numbers

next up previous Next: Other primitive data types Up: Unit 04 Previous: Expressions with side-effect and

Definition of constants and magic numbers

A magic number is a numeric literal that is used in the code without any explanation of its meaning. The use of magic numbers makes programs less readable and hence more difficult to maintain and update.

Example:

int salary = 20000 * workedhours; // what is the meaning of 20000?

It is better to define symbolic names, so called constants, and use these instead of numeric literals.

// definition of a constant SALARY_PER_HOUR final int SALARY_PER_HOUR = 20000; ... // now it is clear what SALARY_PER_HOUR means int salary = SALARY_PER_HOUR * workedhours;

SALARY_PER_HOUR is a constant, which in Java is a variable whose content does not change during the execution of the program. We can declare a constant by using the modifier final in the variable declaration, which indicates that the value of the variable cannot be modified (i.e., it stays constant).

The main advantages of using constants are:

  • Readability of the program: an identifier of a constant with a significant name is much more readable than a magic number (e.g., SALARY_PER_HOUR is self-explaining, 20000 is not);
  • Modifiability of the program: to modify the value of a constant used in the program it is sufficient to change the definition of the constant (e.g., final int SALARY_PER_HOUR = 35000), while with magic numbers we would have to modify all occurrences of the value in the program (e.g., by replacing occurrences of 20000 con 35000). Notice that it may be difficult to determine which occurrence of the specific magic number actually corresponds to the one we have to change.

Note: The declarations of constants (containing the final modifier) can be dealt with in the same way as variable declarations. Specifically, if the declaration is local to a method, the scope of the constant is the method itself. Instead, if we apply the final modifier to the declaration of an instance variable, then the constant will be associated to each object the moment it is created, and different objects may have different values for the constant.

next up previous Next: Other primitive data types Up: Unit 04 Previous: Expressions with side-effect and

Tag » What Is The Magic Number