Skip Navigation

Using enums to make flat-file parsing in Java more maintainable

Delimited flat-file parsing often leads to brittle index-based code. In this post, I show how enums make field positions easier to read and maintain.

In the examples below, we assume the input has already been split:

 java
    
String[] split = delimitedData.split("\\|");

  

There are caveats of using the split method this way, but they are outside the scope of this post.

Direct indexing

 java
    
DbData existingData = dbHandler.getExistingData(
    split[2],
    split[7],
    split[8],
    split[9]
);

  

Direct indexing is compact, but brittle and hard to scan.

Local variables

 java
    
String id = split[2];
String date = split[7];
String time = split[8];
String reason = split[9];

DbData existingData = dbHandler.getExistingData(
    id, 
    date, 
    time, 
    reason
);

  

Local variables improves readability at the call site, but field mappings are still scattered across the code base.

Enum mapping

 java
    
public enum FlatFileField {
    ID(2),
    DATE(7),
    TIME(8),
    REASON(9);

    private final int index;

    FlatFileField(int index) {
        this.index = index;
    }

    public int index() {
        return index;
    }
}

DbData existingData = dbHandler.getExistingData(
    split[FlatFileField.ID.index()],
    split[FlatFileField.DATE.index()],
    split[FlatFileField.TIME.index()],
    split[FlatFileField.REASON.index()]
);

  

Comparison

ApproachProsCons
Direct indexingConciseUses magic numbers, hard to maintain, higher cognitive load
Local variablesReadable at call siteField mapping still scattered
Enum mappingCentralized field positions, clearer intentRequire an additional enum

Takeaway

Enums are a simple way to replace magic numbers with meaningful names when working with delimited data. They improve readability and centralize field positions. When parsing logic grows beyond simple positional access, a dedicated parser or DTO is usually a better choice.

Comments

10

Comments

10