buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

hard-coded strings are a bad idea.

Hard-Coding is a terribly bad practice.  Look at the code bellow.  The programmer hard coded the strings in the program.  String like "huiQiTransPaymentService" refers to a bean named  HuiQiTransPaymentService .

When a code refactoring occurs, for example, the name of the class " HuiQiTransPaymentService " is modified, whereas the string here may be forgotten.  At this time, a potential bug has arisen. At some time later, you'll unfortunately encounter  NoSuchBeanDefinitionException .

public static final Map<FunCodeEnum, String> FUN_CODE_ENUM_MAP;

static {
    FUN_CODE_ENUM_MAP = new HashMap<>();
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.PAYMENT, "huiQiTransPaymentService");
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.PAYMENT_QUERY, "huiQiTransPaymentQueryService");
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.BALANCE_QUERY, "huiQiMerBanlceQueryService");
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.SIGN_CONTRACT, "huiQiSignService");
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.SIGN_CONTRACT_QUERY, "huiQSignQueryService");
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.QUERY_ELECTRIC_RECEIPT, "huiQQueryTransReceiptService");
}

 

How to optimize these hard codes?

The answer is using Class instead of String.  See bellow.

public static final Map<FunCodeEnum, Class> FUN_CODE_ENUM_MAP;

static {
    FUN_CODE_ENUM_MAP = new HashMap<>();
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.PAYMENT,  HuiQiTransPaymentService.class);
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.PAYMENT_QUERY, HuiQiTransPaymentQueryService.class);
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.BALANCE_QUERY, HuiQiMerBanlceQueryService.class);
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.SIGN_CONTRACT, HuiQiSignService.class);
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.SIGN_CONTRACT_QUERY, HuiQSignQueryService.class);
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.QUERY_ELECTRIC_RECEIPT, HuiQQueryTransReceiptService.class);
}

 

By the way, according to the fact that these classes implement the same interface  HuiQiBusinessService , this program can be refactored more explicit and readable.

public static final Map<FunCodeEnum, Class<? extends HuiQiBusinessService>> FUN_CODE_ENUM_MAP;

static {
    FUN_CODE_ENUM_MAP = new HashMap<>();
    FUN_CODE_ENUM_MAP.put(FunCodeEnum.PAYMENT,  HuiQiTransPaymentService.class);
    ...
}

 

 

 

 

 

posted on 2023-03-06 20:00  buguge  阅读(22)  评论(0编辑  收藏  举报