enum

This lesson explains enum, its use and properties.

enum #

enum is the feature that enables defining named constant values.

Effects of magic constants on code quality #

Let’s have a look at this code:

Press + to interact
import std.stdio;
void main() {
int first = 16;
int second = 8;
int result;
int operation = 2;
if (operation == 1) {
result = first + second;
} else if (operation == 2) {
result = first - second;
} else if (operation == 3) {
result = first * second;
} else if (operation == 4) {
result = first / second;
}
writeln(result);
}

The integer literals 1, 2, 3 and 4 in the code above are called magic constants. It is not easy to determine what each of those literals mean in the program. One must examine the code in each scope to determine that 1 means addition, 2 means subtraction and so on. This task is relatively easy for the above code because all of the scopes contain just a single line. It would be considerably more difficult to decipher the meanings of magic constants in longer and complex programs.
Magic constants must be avoided because they impair two important qualities of source code:

  • readability

  • maintainability

enum enables names to be given to these constants and, consequently, makes the code more readable and maintainable. Each condition would be readily understandable if the following enum constants were used:

if (operation == Operation.add) { 
    result = first + second;

} else if (operation == Operation.subtract) { 
    result = first - second;

} else if (operation == Operation.multiply) { 
    result = first * second;

} else if (operation == Operation.divide) {
    result = first / second; 
}

The enum type Operation used above obviates the need for magic ...

Access this course and 1400+ top-rated courses and projects.