Sobes.tech
Junior — Middle

Can you explain the concept of Pattern String Enum and its advantages?

sobes.tech AI

Answer from AI

Pattern String Enum is an approach in Java where, instead of using a standard enum with fixed values, a class is created with a set of static string constants that mimic an enumeration. This pattern is useful when you need a set of fixed string values but also want greater flexibility, such as the ability to extend the set of values without recompilation.

Advantages:

  • You can use strings directly, which is convenient for integration with external systems (e.g., JSON, databases).
  • It's easy to extend the set of values without changing the enum.
  • You can add methods and logic that are not available in standard enums.

Example:

public class Status {
    public static final String NEW = "NEW";
    public static final String IN_PROGRESS = "IN_PROGRESS";
    public static final String DONE = "DONE";

    private Status() {} // prevent instantiation
}

This approach is often used when values come from external sources and are not fixed at compile time.