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); ... }
当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--buguge
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/p/17185212.html