Backend Development 8 min read

Improving Java Backend Code Readability with Enums and Proper Value Matching

This article discusses common pitfalls in Java code such as string and numeric matching, explains why using raw literals can cause bugs, and demonstrates how to improve readability and maintainability by employing enums, value conversion, and state‑machine patterns for backend development.

Architecture Digest
Architecture Digest
Architecture Digest
Improving Java Backend Code Readability with Enums and Proper Value Matching

In Java backend projects, developers often use literal identifiers such as <男,女> or <正常,删除> that are stored in databases as numeric codes, but the way these identifiers are handled in code can lead to serious bugs and reduced readability.

One common mistake is direct string comparison. The following code shows converting gender strings to numeric codes and then comparing them with == or equals :

//如果sex是字符串,java中可以通过==对比值吗?
if(user.getSex() == "1"){
    //todo 如果是男生
}
//Sex 是字符串类型eq方法中传入1会返回true吗?
if(user.getSex().equals(1)){
    //todo 如果是男生
}

This approach suffers from null‑pointer risks, improper use of == for string values, and the fact that String.equals(Object) will return false when comparing a string with an integer, which can easily introduce hidden bugs.

Numeric comparison also has traps. The code below demonstrates surprising results when using == on Integer objects:

Integer man = 200;
Integer sex = 200;
System.out.println(man == sex); // false
Integer man1 = 2;
Integer sex1 = 2;
System.out.println(man1 == sex1); // true

The difference arises from Java's IntegerCache which caches values in the range [-128, 127]; values outside this range are distinct objects, so == yields false.

To avoid these issues, the article recommends using enums that map directly to database fields. An example enum for gender is shown:

import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.HashMap;
public class UserEnum {
    @Getter
    @AllArgsConstructor
    public enum Sex {
        Man(1, "男"), WOMAN(2, "女");
        public Integer code;
        public String msg;
        private static HashMap
data = new HashMap<>();
        static {
            for (Sex d : Sex.values()) {
                data.put(d.code, d);
            }
        }
        public static Sex parse(Integer code) {
            return data.getOrDefault(code, null);
        }
    }
    // other enums like Status, Role can be defined similarly
}

Using such enums ensures a single source of truth for status codes, improves readability, and prevents mismatches between developers.

Conversion from numeric codes received from the front end to enums is straightforward:

public static void main(String[] args) {
    // client sends status code 1
    Integer man = 1;
    UserEnum.Sex parse = UserEnum.Sex.parse(man);
    System.out.println(parse);
}

Enums can also be used in switch statements:

public static void main(String[] args) {
    Integer man = 1;
    UserEnum.Sex parse = UserEnum.Sex.parse(man);
    switch (parse) {
        case Man:
            // todo
            break;
        case WOMAN:
            // todo
            break;
    }
}

For more complex workflows, an enum‑based state machine can encapsulate transition logic. The following example models an approval process with abstract getNextStatus implemented by each enum constant:

import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ApprovalStatusEnum {
    START(1, "开始审批") {
        @Override
        ApprovalStatusEnum getNextStatus() { return first_leader; }
    },
    first_leader(2, "第一个领导审批") {
        @Override
        ApprovalStatusEnum getNextStatus() { return second_leader; }
    },
    second_leader(3, "第二个领导审批") {
        @Override
        ApprovalStatusEnum getNextStatus() { return backups; }
    },
    backups(4, "备案") {
        @Override
        ApprovalStatusEnum getNextStatus() { return null; }
    };
    private Integer code;
    private String msg;
    abstract ApprovalStatusEnum getNextStatus();
}

Defining abstract methods within enums and providing concrete implementations for each state makes large‑scale state transitions (e.g., approval, payment) clearer and easier to maintain.

Overall, replacing raw literals with well‑designed enums, understanding Java's object comparison semantics, and leveraging enum‑based state machines significantly improve code readability, safety, and maintainability in backend Java projects.

BackendJavabest practicescode readabilityenums
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.