buguge - Keep it simple,stupid

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

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

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   buguge  阅读(26)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2020-03-06 后端接口响应很快,页面呈现却很慢,咋回事?当事人更清楚
点击右上角即可分享
微信分享提示