作者:微信文章
以下是一段重构之前的Java代码:public class BankEventType {
public static final int SHOW_BANK_ACCOUNT = 1; public static final int CANCEL_BANK_ACCOUNT = 2; public static final int ALTER_BANK_ACCOUNT = 3; public static final int SHOW_LOAN_DETAIL = 4; public static final int CANCEL_LOAN_APPLICATION = 5; public static final int ALTER_LOAN_TERMS = 6; public static final int EXPORT_TRANSACTION_REPORT = 7;
public static int getEventType(String actionName) throws Exception { int actionKey; if(actionName == null) { actionKey = SHOW_BANK_ACCOUNT; } else if("show_bank_account".equals(actionName)) { actionKey = SHOW_BANK_ACCOUNT; } else if("cancel_bank_account".equals(actionName)) { actionKey = CANCEL_BANK_ACCOUNT; } else if("alter_bank_account".equals(actionName)) { actionKey = ALTER_BANK_ACCOUNT; } else if("show_loan_detail".equals(actionName)) { actionKey = SHOW_LOAN_DETAIL; } else if("cancel_loan_application".equals(actionName)) { actionKey = CANCEL_LOAN_APPLICATION; } else if("alter_loan_terms".equals(actionName)) { actionKey = ALTER_LOAN_TERMS; } else if("export_transaction_report".equals(actionName)) { actionKey = EXPORT_TRANSACTION_REPORT; } else { throw new Exception("Invalid action name"); } return actionKey; }}
上述代码中,大量重复同一个行为:数据转换,通过大量的if-else if去做该行为,在代码上看着是很繁琐的,可以通过将数据封装分离,与统一的行为隔开,对代码进行优化,让代码具有更好的可读性和可维护性,修改后的代码如下:
import com.google.common.collect.Maps;import java.util.Map;import java.util.Optional;
public class BankEventType {
public static final int SHOW_BANK_ACCOUNT = 1; public static final int CANCEL_BANK_ACCOUNT = 2; public static final int ALTER_BANK_ACCOUNT = 3; public static final int SHOW_LOAN_DETAIL = 4; public static final int CANCEL_LOAN_APPLICATION = 5; public static final int ALTER_LOAN_TERMS = 6; public static final int EXPORT_TRANSACTION_REPORT = 7;
public final static Map<String, Integer> EVENT_ACTION_MAP = Maps.newHashMap();
static { EVENT_ACTION_MAP.put(null, SHOW_BANK_ACCOUNT); EVENT_ACTION_MAP.put("show_bank_account", SHOW_BANK_ACCOUNT); EVENT_ACTION_MAP.put("cancel_bank_account", CANCEL_BANK_ACCOUNT); EVENT_ACTION_MAP.put("alter_bank_account", ALTER_BANK_ACCOUNT); EVENT_ACTION_MAP.put("show_loan_detail", SHOW_LOAN_DETAIL); EVENT_ACTION_MAP.put("cancel_loan_application", CANCEL_LOAN_APPLICATION); EVENT_ACTION_MAP.put("alter_loan_terms", ALTER_LOAN_TERMS); EVENT_ACTION_MAP.put("export_transaction_report", EXPORT_TRANSACTION_REPORT); }
public static int getEventType(String actionName) throws Exception { return Optional.ofNullable(EVENT_ACTION_MAP.get(actionName)) .orElseThrow(() -> new Exception("Invalid action name")); }}
通过map将数据封装,统一的转换行为通过map自身的映射功能去获取即可。