Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java enum constant bodies: keep each fee rule with its tier

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

An enum constant can provide its own implementation of an abstract method. This binds a finite set of named choices to distinct behavior without string-based branching elsewhere.

Operational contract

The tier validates parcel grams at the method entry, then each constant computes its own fee with checked arithmetic. The formulas are policy examples: STANDARD charges 47 cents per kilogram rounded up, and EXPRESS charges 82 cents per kilogram rounded up. The result of 1,001 grams is two kilograms by policy. Enum constants are singletons, so do not place mutable per-request state inside a constant body. Adding a tier still requires a business review of callers and persisted names.

Failure case

A 1,001-gram parcel costs 94 cents at STANDARD or 164 cents at EXPRESS. If fees change, the code review can see the two named policies separately. The method rejects negative or over-47,000-gram inputs before pricing.

Java code

Java
public class ParcelTierFees {
    public enum Tier {
        STANDARD { @Override long centsPerKilogram() { return 47; } },
        EXPRESS { @Override long centsPerKilogram() { return 82; } };

        abstract long centsPerKilogram();

        public long fee(int grams) {
            if (grams < 0 || grams > 47_000)
                throw new IllegalArgumentException("Mass outside policy");
            long kilograms = (grams + 999L) / 1_000L;
            return Math.multiplyExact(kilograms, centsPerKilogram());
        }
    }
}

Performance and ownership cost

Selection, integer rounding, and multiplication are O(1) time with O(1) extra space. The enum instances are initialized once. The 47,000-gram cap bounds the result here, while multiplyExact keeps later policy changes from silently overflowing.

Common Mistakes

  • Do not store mutable request data on a shared enum constant.
  • Do not divide before adding the rounding offset when the policy requires ceiling.
  • Do not persist enum names as an unreviewed long-term compatibility contract.

Connected lessons

java
metadata and constant behavior
enum-constant-specific-fee
Storage details