Enumerated Types

What are enumerated types?

It's very common to encounter situations where the data you want to model is a finite set of named items, such as days of the week (sunday, monday, tuesday, etc), months in the year, colors in the rainbow, positions on a baseball team, or names of U.S. coins (penny, nickel, dime, quarter, dollar). Because every possible value of the type can be named, we say the data are enumerable, and call the type an enumerated type. (As distinguished from integer, for example, which has infinite possible values).

Imagine a payroll program where the user enters a timecard which shows how many hours worked and the day of the week. Say that overtime pay is given for work on the weekends. How do we represent the day of the week type? That is, what kind of variable do we use to store a day?

The crude solution

A cumbersome and ineffective solution is to arbitrarily assign an integer to each enumeration value. Thus Sunday = 1, Monday = 2, Tuesday = 3, etc. With this solution we say that days of the week and integer are at "different levels of abstraction" and thus demands a small part of the programmer's mental resources to "translate" an integer into the value in the problem domain. For example, if you read the coding "if (Today = 5)" you have to take a moment to translate 5 into its day value, and you might make a mistake. Another drawback is that there is nothing to prevent accidentally assigning "Today = 100;" which has no meaning in the problem domain and is probably an error.

Thus this approach is error-prone, difficult to read, and difficult to maintain.

A minor improvement

Declare constants for each possible enumeration value, for example

final static int Sunday = 1;
final static int Monday = 2;

This allows you to at least refer to names instead of numbers, but still provides no real data integrity. One could accidentally assign 100 to Today.

The best solution

To take advantage of the power of abstraction, many languages have a facility for programmer-defined enumerated types. For example,

// C++
enum DaysOfTheWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

-- Ada
TYPE DaysOfTheWeek is (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);

/* C */
typedef enum
{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
DaysOfTheWeek ;

Then the code can be written simply and obviously:

DaysOfTheWeek Today;
....
if (Today == Saturday || Today == Sunday) 

/*  do overtime calculations */

Ada also has built-in functions for getting "previous" and "next" values, and for input/output of enumeration values.

Java has built-in enumerated types starting with JDK1.5.