Explain Codes LogoExplain Codes Logo

Naming of enums in Java: Singular or Plural?

java
best-practices
naming-conventions
enums
Nikita BarsukovbyNikita Barsukov·Dec 10, 2024
TLDR

Opt for singular in enums as good practice, each constant typically embodies a sole concept. Use plural strictly when the constants embody a group concept, like permissions, providing clarity in their collective intention.

Singular (widely used):

public enum Shade { RED, GREEN, BLUE; // Each color shines in its singularity }

Plural (when representing a set):

public enum FileAccess { READ, WRITE, DELETE; // A set of permissions longing for CRUD operation love }

When to use singular or plural

In choosing between singular and plural, consider the enum's specific context. Constants should be semantically tethered to the enum's name. Use this guide to decide on the right form:

Singular - for individual concepts:

enum Day { MONDAY, TUESDAY, WEDNESDAY; // Individual days because they're just too unique }

Plural - for collectives or collections:

enum Permissions { READ, WRITE, EXECUTE; // Group of permissions trying to protect data integrity }

Liase naming standards with contextual clarity. Enums are principally used to express constant sets—like days, colors, or directions.

Flags enums: still singular

Sticking with the singular form even when an enum acts as a set of flags (with binary operations) helps maintain consistency. Witness the example:

public enum Permission { READ(1), WRITE(2), EXECUTE(4); // We are ONE, but to serve MANY private final int bits; Permission(int bits) { this.bits = bits; } public int getBits() { return bits; } }

Even when we're looking at multiple values, a flags enum in Java can be memory efficient if modeled as a List or Set.

Enums within classes

Enums contained within a class or interface should adhere to the same naming conventions. An enclosed enum represents a category that's a feature of the parent type:

public class Printer { enum ColorMode { BLACK_AND_WHITE, COLOR, GRAYSCALE; // Color printing is within my league of responsibilities } // ... }

Notice how ColorMode perfectly befits the Printer class sans the need for a plural form.

In the domain-specific context...

Sometimes, there exist naturally plural domain-specific terms. In such cases, it's best to stick with what makes sense within that domain context:

Exceptional cases:

enum Series { TRILOGY, DUOLOGY, ANTHOLOGY; // Because a Trilogy isn't just a 'one-off' }

In such special circumstances, the best practice aligns with the domain-speak for intuitive API usage.