Providing Enum Consistency Between Application and Data
Discussing and demonstrating the Spring Boot application of a solution for providing enum consistency between running the application code and data itself.
Join the DZone community and get the full member experience.
Join For FreeEnum usage is a very common practice in the software world that helps write high-quality and low-maintenance code. However, enum values that are not kept in any place (Database, file, etc.) other than the code, make the monitoring and interpretation of data strictly dependent on the application code itself.
The Problem
Let’s consider a table like this:
When we look at the data, it is quite possible to reach a general conclusion that the table is “a table that holds the payment preferences of the customers.” However, when we dive into the details of the records, it is difficult to determine which payment type is preferred based on a customer. Due to the normalization principles, we cannot fill these columns as repeating “text” expressions. So, to make the data meaningful, giving a reference to an external source is essential.
Defining the Solution
The following solutions will address the problem above:
- Inserting a description to a column as metadata. (It is static information and requires constant manual follow-up. If the maintenance cost is high, it is difficult to keep the metadata up to date. It may be used to statically refer to the source of dimension information).
- Hosting separate dimension tables. (It is costly to maintain a separate table for each enumeration. There is a risk of increasing the data model complexity. It can be taken into account for dimension data with a high number of values).
- A separate table where such enums are grouped and hosted collectively. (Ideal for relatively small dimension groupings. If its alignment with the application is broken, it will not serve for the interpretation of the data anymore).
We can think that a certain and reasonable mix of these three can be used in large applications at the enterprise level. In this article, we will discuss how the third reference source can be used in a way that eliminates the risk stated in the item description with hands-on code samples.
Environment Info
For the sake of being on the same page regarding the code samples being delivered in this article, below is our development environment information:
OS: Windows 10 20H2
IDE: IntelliJ IDEA 2022.2.1 (Ultimate Edition)
Java: 17
Spring Boot: 3.0.1
Apache Maven: 3.8.6
Code samples will be delivered under the sections when needed for clarity. Also, the full source code in which implementations of the ideas delivered in this article can be accessed from my GitHub repo.
Dimension Data Reference Source
Reference data should be located outside of the application context, which may be in a database table, cache, or file. For instance, the dimension data subject to the problem given above can be stored in table name Enum as follows:
Since retrieving the reference data from an external resource as a data source, cache, file, etc., is out of the scope of this article, we will use a mock service that will return data as follows:
@Service
public class EnumService {
public List<Enum> getEnumList() {
return Arrays.asList(Enum.builder().group("STATUS").name("ACTIVE").value("1").build(),
Enum.builder().group("STATUS").name("PASSIVE").value("0").build(),
Enum.builder().group("PAYMENT_TYPE").name("CASH").value("1").build(),
Enum.builder().group("PAYMENT_TYPE").name("MOBILE_PAYMENT").value("2").build(),
Enum.builder().group("PAYMENT_TYPE").name("CREDIT_CARD").value("3").build());
}
}
Defining Enums
Originating from the previous topic and the problem mentioned in the first part, let’s define the following two enum classes:
The Status Enum
@Getter
@AllArgsConstructor
@MyEnum
@AutoConfigureBefore(EnumValidation.class)
public enum Status implements IEnum<Status> {
ACTIVE("1"),
PASSIVE ("0");
private final String value;
@Override
public Status getByValue(String value) {
return Arrays.stream(Status.values())
.filter(status -> status.getValue().equals(value))
.findFirst()
.orElse(null);
}
@MyEnumValidation
@Override
public void validateEnum(List<Enum> enumDefinitionList) {
List<Enum> enumAsList = Arrays.stream(Status.values())
.map(paymentType -> Enum.builder()
.name(paymentType.name())
.value(paymentType.getValue()).build()).toList();
EnumValidation.validateEnum(Status.this.getClass(), enumDefinitionList, enumAsList);
}
}
The PaymentType Enum
@Getter
@AllArgsConstructor
@MyEnum
@AutoConfigureBefore(EnumValidation.class)
public enum PaymentType implements IEnum<PaymentType> {
CASH("1"),
MOBILE_PAYMENT("2"),
CREDIT_CARD ("3");
private final String value;
@Override
public PaymentType getByValue(String value) {
return Arrays.stream(PaymentType.values())
.filter(status -> status.getValue().equals(value))
.findFirst()
.orElse(null);
}
@MyEnumValidation
@Override
public void validateEnum(List<Enum> enumDefinitionList) {
List<Enum> enumAsList = Arrays.stream(PaymentType.values())
.map(paymentType -> Enum.builder()
.name(paymentType.name())
.value(paymentType.getValue()).build()).toList();
EnumValidation.validateEnum(PaymentType.this.getClass(), enumDefinitionList, enumAsList);
}
}
Let’s talk about the @MyEnum
and @MyEnumValidation
annotations and the IEnum
interface that stand out in these classes.
The @MyEnum
annotation allows us to distinguish that the annotated enum class must be validated with a reference data source.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyEnum {
}
The @MyEnumValidation
annotation means that the annotated method can be used to validate the values of the enum class.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyEnumValidation {
}
Finally, IEnum
is a contract that we want our enum classes to comply with.
public interface IEnum<T> {
String getValue();
T getByValue(String value);
void validateEnum(List<Enum> enumList);
}
After defining our enum definitions, reference sources, and making the necessary implementations, let’s explain the mechanism that will compare and validate these two sources.
Validating Code Against Reference Data
If there is an inconsistency between the code and the reference data (i.e. we implemented the Cash payment type as 23 in the code, but there is another value in our reference source), our Spring Boot application should not deploy. To accomplish this, a @Configuration
annotated enum classes will be collected and the validation methods will be triggered to validate each of them as follows:
@PostConstruct
private void validateEnums() {
final List<Enum> enumList = enumService.getEnumList();
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(PACKAGE_NAME.replaceAll("[.]", "/"));
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
Set<Class> classSet = reader.lines()
.filter(line -> line.endsWith(".class"))
.map(this::getClass)
.filter(enumClass -> enumClass.isEnum() && enumClass.isAnnotationPresent(MyEnum.class))
.collect(Collectors.toSet());
for (Class enumClass : classSet.stream().toList()) {
Method validationMethod = Arrays.stream(enumClass.getMethods())
.filter(method -> method.isAnnotationPresent(MyEnumValidation.class))
.findAny()
.orElseThrow(() -> new RuntimeException(enumClass.getSimpleName() + " enum has no validation method!"));
try {
if (enumClass.getEnumConstants().length > 0) {
validationMethod.invoke(enumClass.getEnumConstants()[0], enumList);
}
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
@MyEnumValidation
annotated method of each enum class. Make a final comparison of the enum values in the code with the values from the reference source as follows:
public static void validateEnum(Class enumClass, List<Enum> enumDefinitionList, List<Enum> enumList) {
final String enumGroup = enumClass.getSimpleName()
.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2")
.replaceAll("([a-z])([A-Z])", "$1_$2")
.toUpperCase(Locale.ROOT);
for (Enum enumItem : enumList) {
boolean missingEnumDefinition = enumDefinitionList.stream()
.noneMatch(enumDefiniton ->
enumDefiniton.getGroup().equals(enumGroup) &&
enumDefiniton.getName().equals(enumItem.getName()) &&
enumDefiniton.getValue().equals(enumItem.getValue()));
if (missingEnumDefinition) {
throw new RuntimeException("Enum definition not found in data source! Enum Group: " + enumGroup + " Enum Item: " + enumItem.getName() + " Enum Value: " + enumItem.getValue());
}
}
}
Note: the enum group is the SNAKE_CASE
equivalent of the enum class name itself. The name value is the name of the fields in the enum and the value values are the values assigned to the enum fields.
Test
If we run our application with the consistent enum-reference source values described so far, the application will start up without error as follows:
For testing purposes, the data retrieved from the reference source mock service is changed as follows (the value of the Active enum in the Status group, which should have been 1, became 12):
public List<Enum> getEnumList() {
return Arrays.asList(Enum.builder().group("STATUS").name("ACTIVE").value("12").build(),
Enum.builder().group("STATUS").name("PASSIVE").value("0").build(),
Enum.builder().group("PAYMENT_TYPE").name("CASH").value("1").build(),
Enum.builder().group("PAYMENT_TYPE").name("MOBILE_PAYMENT").value("2").build(),
Enum.builder().group("PAYMENT_TYPE").name("CREDIT_CARD").value("3").build());
}
As a result, when we run our application, it will throw an error as shown below and will not start:
Conclusion
In this article, we have simulated a solution proposal on how to keep the dimension data aligned between the application code and the data source.
The full application code can be accessed from my GitHub profile.
Opinions expressed by DZone contributors are their own.
Comments