DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Data
  4. Providing Enum Consistency Between Application and Data

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.

Taner Inal user avatar by
Taner Inal
·
Dec. 28, 22 · Tutorial
Like (1)
Save
Tweet
Share
3.61K Views

Join the DZone community and get the full member experience.

Join For Free

Enum 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:

Table

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: 

  1. 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).
  2. 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).
  3. 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:

Enum Table

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: 

Java
 
@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

Java
 
@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

Java
 
@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 @MyEnumand @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.

Java
 
@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.

Java
 
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyEnumValidation {
}


Finally, IEnum is a contract that we want our enum classes to comply with.

Java
 
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:

Java
 
@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: 

Java
 
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:

Error

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):

Java
 
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: Thrown Error

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. 

Apache Maven Database application Data (computing) Java (programming language) Data Types Metadata Cache (computing) Spring Boot

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Is DevOps Dead?
  • Seamless Integration of Azure Functions With SQL Server: A Developer's Perspective
  • Old School or Still Cool? Top Reasons To Choose ETL Over ELT
  • NoSQL vs SQL: What, Where, and How

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: