I see this pattern a lot, especially with countries, or more generally regions. An enum is defined with additional fields and with methods that translate to and from these values.
Example:
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Arrays;
@AllArgsConstructor
public enum Country {
AFGHANISTAN("Afghanistan"),
ALBANIA("Albania"),
ALGERIA("Algeria"),
//...
ZAMBIA("Zambia"),
ZIMBABWE("Zimbabwe");
@Getter
private final String countryName;
public static Country fromName(String name) {
return Arrays.stream(values())
.filter(v -> v.getCountryName().equals(name))
.findFirst()
.orElse(null);
}
}
Other and additional fields are possible, e.g. ISO country codes or company internal country codes. While there are several reasons to add fields to an enum, I’m talking specifically about cases where this is used to translate between domains or layers. E.g. If an enum is stored in the database as a String you can now use the enum itself for conversion from and to a String. Same if you receive Strings in requests to your API. And if you need to translate between domains, e.g. in an anti-corruption layer you can also do that with such an enum.
All of this could be done with mappers of course, I assume the benefits of defining it directly in the enum are:
- High cohesion. Everything related to mapping is in the same class => if the mapping changes you are less likely to forget updating a mapping
- Type Guarantees. By making the mapping part of the type you get guarantees that the mapping is complete, for example.
- No need to use mappers if you can’t or don’t want to.
As disadvantages I see
- The enum knows more about other domains than it should
- Complexity. Developers may not expect an Enum to do so much
Does this pattern have a name?
2
This recurring pattern might not have a name. But what you’re seeing is stringly typed strings being converted into types. This example just happens to use enums.
The danger of this pattern is that while it does create a strongly typed area of code there still remains code outside that area where weird things can still happen. Like arguments about how Turkey is spelled.
Look into internationalization strategies to see ways to squeeze this confusion out of your codebase. Strings just don’t make good types. But they’re really good at pretending they do. That’s the danger.