Explain Codes LogoExplain Codes Logo

Coding Conventions - Naming Enums

java
naming-conventions
enums
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 8, 2024
TLDR

In Java, enums should follow a UPPER_CASE naming convention just like constants. This reinforces their immutable nature in the eyes of fellow developers and aligns with the Java Language Specification:

public enum Color { RED, // as red as an embarrassed tomato GREEN, // as green as Kermit the Frog BLUE; // as blue as a smurf's bottom }

For enums with compound names, remember that readability is king. Therefore, you can opt for UPPER_CASE or play with Mixed_Case to make it easy on the eyes:

public enum HttpStatus { OK, // when everything is just fine and dandy NOT_FOUND, // hide and seek champion BAD_REQUEST; // smelly requests end up here }

Using meaningful and descriptive names is better than sticking a dull "Enum" at the end.

Avoid confusion with class naming

Sometimes, enums could share a similar identity with a class, causing a naming clash. To avoid confusion, differentiate with context and usage:

public class NetworkConnection { // this class is doing all the hard work ... } public enum NetworkConnectionType { // the VIP list of network connections WIFI, ETHERNET, LTE; }

With distinguishable and clear names, one can easily tell a model or utility (NetworkConnection) apart from a set of predefined options (NetworkConnectionType).

Balancing brevity and clarity

In your pursuit of the perfect enum name, always strike a balance between brevity and descriptiveness:

public enum State { NEW, // fresh out of the oven ACTIVE, // out and about INACTIVE, // low energy saving mode DELETED; // guess who saw the grim reaper } // Instead of public enum StateOfObject { STATE_NEW, STATE_ACTIVE, STATE_INACTIVE, STATE_DELETED; // verbosity at its finest }

State is simple and conveys as much information as the verbose StateOfObject.

Making it chime with methods

Remember that the naming choice for enums can affect their interaction with certain methods like .name(), which returns the enum constant's name as a String:

public enum Fruit { APPLE, // An apple a day... BANANA, // and a banana for breakfast! CHERRY; // save the cherry for last } Fruit cherry = Fruit.CHERRY; System.out.println(cherry.name()); // Prints "CHERRY"

Capitalizing your enums correctly ensures both the consistency and predictability of your code.