Course contentsShow
← Java
Lesson 607 of 2,87014. EnumerationsFree lesson

Why ordinal() Should Be Avoided in Business Logic

Understand the fragility of ordinal-based code and why reordering enum constants breaks existing logic.

Why ordinal() Should Be Avoided in Business Logic

You'll learn why relying on ordinal() in your business logic creates fragile, maintenance-prone code.

The Fragility Problem

In the previous lesson, you learned that ordinal() returns the zero-based position of an enum constant in its declaration order. While this might seem useful, hardcoding logic based on these positions is extremely fragile.

Here's why: enum constants can be reordered. When you or a teammate rearranges the declaration order (perhaps to group related constants, or alphabetize them), every ordinal() value changes—and any business logic depending on those ordinals instantly breaks.

The Invisible Danger

Imagine you write code checking if (priority.ordinal() < 2) to handle high-priority tasks, where Priority.HIGH is declared first with ordinal 0 and Priority.MEDIUM second with ordinal 1. Months later, someone adds Priority.URGENT at the beginning. Now HIGH has ordinal 1, and your condition suddenly excludes it. The compiler won't warn you—your logic just silently behaves incorrectly.

Analogy: House Numbers That Change

Think of ordinal() like house numbers on a street where the city renumbers houses whenever someone builds a new one. You tell a friend "I live at house #3," but next month that address might be different. Instead, use a stable identifier (like "123 Oak Street") that never changes—in Java, that means explicit fields or the constant identity itself.

The Right Approach

Store meaningful data in enum fields. Instead of comparing ordinals, compare field values or use constant-specific logic. If you need ordering, declare an explicit priority field with stable values that won't change when you reorder declarations.

Key Takeaway: Avoid ordinal() in business logic because reordering enum constants silently breaks ordinal-based code without compiler warnings—use explicit fields instead.