首页 > 解决方案 > How to handle thousands of error message constant in java?

问题描述

My app is sending request to APIs from some other parties. Every single parties have different return codes that I need to handle. The result is I need to handle thousands of different return code from those parties.

I am thinking about making a specific class that will hold constant to handle all of them. It will be like:

public static final Map<String, String>  RETURN_CODE_MAP = new HashMap<String, String>(){
    {
        // these mapping will be thousands of line
        put("BANK_A_000","SUCCESS");
        put("BANK_A_001","FAILED");
        put("BANK_A_002","UNKNOWN");
        put("BANK_B_SU","SUCCESS");
        put("BANK_B_FA","FAILED");
        put("BANK_B_UN","UNKNOWN");
        put("BANK_C_00077","SUCCESS");
        put("BANK_C_00088","FAILED");
        put("BANK_C_00099","UNKNOWN");
        put("E-COMMERCE_A_000","SUCCESS");
        put("E-COMMERCE_A_001","FAILED");
        put("E-COMMERCE_A_002","UNKNOWN");
        put("E-COMMERCE_B_000SU","SUCCESS");
        put("E-COMMERCE_B_000FA","FAILED");
        put("E-COMMERCE_B_000UN","UNKNOWN");
        put("E-COMMERCE_C_00077","SUCCESS");
        put("E-COMMERCE_C_00088","FAILED");
        put("E-COMMERCE_C_00099","UNKNOWN");
    }
};

The list of the return code will be thousands of them. Are there going to be a performance issue? Can you guys tell me the right way to handle this kind of case? Thank you all

标签: javaresponseconstants

解决方案


我建议每方使用一个枚举。它使您可以比地图更容易地存储附加信息,并且如果使用正确,可以为您节省一些可能被字符串比较浪费的性能(例如map.get(x).equals("SUCCESS"))。

这可能看起来像这样:

响应状态.java

public enum ResponseStatus {
    SUCCESS,
    FAILED,
    UNKNOWN;
}

银行A.java

import static my.pkg.ResponseStatus;


public enum BankA {

    C_000("000", SUCCESS),
    C_001("001", FAILED),
    C_002("002", UNKNOWN),
    // And so on ...

    private final ResponseStatus status;
    private final int hashCode;

    private BankA(String code, ResponseStatus status) {
        this.status = status;
        this.hashCode = code.hashCode();
    }

    public ResponseStatus getStatus() {
        return this.status;
    }

    public static BankA byStaus(String status) {
        BankA[] values = values();
        int hash = status.hashCode();
        for (int n = 0; n < values.length; n++) {
            BankA value = values[n];
            if (value.hashCode == hash) return value;
        }

        return null; // No entry found by that code
    }

}

请注意,byStatus我比较的是哈希码而不是字符串本身,这比比较数百个字符串要快。

最后,您的最终检查可能如下所示:

BankA status = BankA.byStatus(response);

if (status != null && status.getStatus() == ResponseStatus.SUCCESS) {
    // Do something
}

推荐阅读