Lesson 32Including Magic Numbers and Enums
We use enums to define a set of predefined, related constants. Some common examples include the months of the year and days of the week. In this shorter lesson, we'll look at how to create and use enums. Enums are a construct that allows us to define a group of related constants.
MAGIC NUMBERS
A magic number is a value that is hard-coded into your code but does not have a clear meaning. For example, suppose we had an order-entry system. As each order is processed, it could have a status of Quoted, Purchased, Shipped, or Delivered.
In languages that do not provide enums, a developer will often simply assign a numeric code to each status, so you could end up looking at code such as what is shown in Listing 32.1.
LISTING 32.1
Coding without an Enum
public void shipOrder(Order order) {
if(order.getStatus() == 2) { // purchased
// ship it
// move to shipped status
o.setStatus(3);
}
}
With the comments, the code is clearer, but without the comments, a developer unfamiliar with the order status codes would not know what 2
and 3
mean. This listing might work now, but what happens if a change is needed? Software tends to change over time, so what would we do when we need to add steps in the middle?
For example, what would happen if we needed to add a Gift Wrap stage in between ...
Get Job Ready Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.