實戰|如何消除又臭又長的if...else判斷更優雅的編程?

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最近在做代碼重構,發現了很多代碼的爛味道。其他的不多說,今天主要說說那些又臭又長的if...else要如何重構。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在介紹更更優雅的編程之前,讓我們一起回顧一下,不好的if...else代碼"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"一、又臭又長的if...else"}]},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"廢話不多說,先看看下面的代碼。"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"\npublic interface IPay {\n void pay();\n}@Service\npublic class AliaPay implements IPay {\n @Override\n public void pay() {\n System.out.println(\"===發起支付寶支付===\");\n }}@Service\npublic class WeixinPay implements IPay {\n @Override\n public void pay() {\n System.out.println(\"===發起微信支付===\");\n }}@Service\npublic class JingDongPay implements IPay {\n @Override\n public void pay() {\n System.out.println(\"===發起京東支付===\");\n }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"@Servicepublic class PayService {\n @Autowired private AliaPay aliaPay;\n @Autowired private WeixinPay weixinPay;\n @Autowired private JingDongPay jingDongPay;\n public void toPay(String code) {\n if (\"alia\".equals(code)) {\n aliaPay.pay(); } else if (\"weixin\".equals(code)) {\n weixinPay.pay(); } else if (\"jingdong\".equals(code)) {\n jingDongPay.pay(); } else {\n System.out.println(\"找不到支付方式\");\n } }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"PayService類的toPay方法主要是爲了發起支付,根據不同的code,決定調用用不同的支付類(比如:aliaPay)的pay方法進行支付。這段代碼有什麼問題呢?也許有些人就是這麼幹的。試想一下,如果支付方式越來越多,比如:又加了百度支付、美團支付、銀聯支付等等,就需要改toPay方法的代碼,增加新的else...if判斷,判斷多了就會導致邏輯越來越多?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"很明顯,這裏違法了設計模式六大原則的:開閉原則 和 單一職責原則。"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"❝"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"開閉原則:對擴展開放,對修改關閉。就是說增加新功能要儘量少改動已有代碼。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"單一職責原則:顧名思義,要求邏輯儘量單一,不要太複雜,便於複用。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"❞"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"那有什麼辦法可以解決這個問題呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/c0/c08fce64b8181d02e65f6d06ba001019.webp","alt":"實戰|如何消除又臭又長的if...else判斷更優雅的編程?","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"二、使用註解"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"代碼中之所以要用code判斷使用哪個支付類,是因爲code和支付類沒有一個綁定關係,如果綁定關係存在了,就可以不用判斷了。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們先定義一個註解。"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.TYPE)\npublic @interface PayCode {\n String value();\n String name();\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然後在所有的支付類上都加上註解"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"\n@PayCode(value = \"alia\", name = \"支付寶支付\")\n@Service\npublic class AliaPay implements IPay {\n @Override\n public void pay() {\n System.out.println(\"===發起支付寶支付===\");\n }}@PayCode(value = \"weixin\", name = \"微信支付\")\n@Service\npublic class WeixinPay implements IPay {\n @Override\n public void pay() {\n System.out.println(\"===發起微信支付===\");\n }}@PayCode(value = \"jingdong\", name = \"京東支付\")\n@Service\npublic class JingDongPay implements IPay {\n @Override\n public void pay() {\n System.out.println(\"===發起京東支付===\");\n }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然後增加最關鍵的類:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"@Service\npublic class PayService2 implements ApplicationListener {\n private static Map payMap = null;\n @Override\n public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {\n ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext(); Map beansWithAnnotation = applicationContext.getBeansWithAnnotation(PayCode.class);\n if (beansWithAnnotation != null) {\n payMap = new HashMap<>();\n beansWithAnnotation.forEach((key, value) -> { String bizType = value.getClass().getAnnotation(PayCode.class).value();\n payMap.put(bizType, (IPay) value); }); } } public void pay(String code) {\n payMap.get(code).pay(); }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"PayService2"},{"type":"text","text":"類實現了"},{"type":"text","marks":[{"type":"strong"}],"text":"ApplicationListener"},{"type":"text","text":"接口,這樣在"},{"type":"text","marks":[{"type":"strong"}],"text":"onApplicationEvent"},{"type":"text","text":"方法中,就可以拿到"},{"type":"text","marks":[{"type":"strong"}],"text":"ApplicationContext"},{"type":"text","text":"的實例。我們再獲取打了PayCode註解的類,放到一個map中,map中的key就是PayCode註解中定義的value,跟code參數一致,value是支付類的實例。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這樣,每次就可以每次直接通過code獲取支付類實例,而不用if...else判斷了。如果要加新的支付方法,只需在支付類上面打上PayCode註解定義一個新的code即可。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"注意:這種方式的code可以沒有業務含義,可以是純數字,只有不重複就行。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"三、動態拼接名稱"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"再看看這種方法,主要針對code是有業務含義的場景。"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"@Service\npublic class PayService3 implements ApplicationContextAware {\n private ApplicationContext applicationContext;\n private static final String SUFFIX = \"Pay\";\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n } public void toPay(String payCode) {\n ((IPay) applicationContext.getBean(getBeanName(payCode))).pay(); } public String getBeanName(String payCode) {\n return payCode + SUFFIX;\n }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們可以看到,支付類bean的名稱是由code和後綴拼接而成,比如:aliaPay、weixinPay和jingDongPay。這就要求支付類取名的時候要特別注意,前面的一段要和code保持一致。調用的支付類的實例是直接從ApplicationContext實例中獲取的,默認情況下bean是單例的,放在內存的一個map中,所以不會有性能問題。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"特別說明一下,這種方法實現了ApplicationContextAware接口跟上面的ApplicationListener接口不一樣,是想告訴大家獲取ApplicationContext實例的方法不只一種。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"四、模板方法判斷"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"當然除了上面介紹的兩種方法之外,spring的源碼實現中也告訴我們另外一種思路,解決if...else問題。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們先一起看看spring AOP的部分源碼,看一下DefaultAdvisorAdapterRegistry的wrap方法"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {\n if (adviceObject instanceof Advisor) {\n return (Advisor) adviceObject;\n } if (!(adviceObject instanceof Advice)) {\n throw new UnknownAdviceTypeException(adviceObject);\n } Advice advice = (Advice) adviceObject; if (advice instanceof MethodInterceptor) {\n // So well-known it doesn't even need an adapter.\n return new DefaultPointcutAdvisor(advice);\n }\n for (AdvisorAdapter adapter : this.adapters) {\n // Check that it is supported.\n if (adapter.supportsAdvice(advice)) {\n return new DefaultPointcutAdvisor(advice);\n }\n }\n throw new UnknownAdviceTypeException(advice);\n }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/94/941c5ec266cf860535f373d5ee988c22.webp","alt":"實戰|如何消除又臭又長的if...else判斷更優雅的編程?","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"重點看看supportAdvice方法,有三個類實現了這個方法。我們隨便抽一個類看看"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"class AfterReturningAdviceAdapter implements AdvisorAdapter, Serializable {\n @Override\n public boolean supportsAdvice(Advice advice) {\n return (advice instanceof AfterReturningAdvice);\n } @Override\n public MethodInterceptor getInterceptor(Advisor advisor) {\n AfterReturningAdvice advice = (AfterReturningAdvice) advisor.getAdvice(); return new AfterReturningAdviceInterceptor(advice);\n }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"該類的supportsAdvice方法非常簡單,只是判斷了一下advice的類型是不是AfterReturningAdvice。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們看到這裏應該有所啓發。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其實,我們可以這樣做,定義一個接口或者抽象類,裏面有個support方法判斷參數傳的code是否自己可以處理,如果可以處理則走支付邏輯。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"每個支付類都有一個support方法,判斷傳過來的code是否和自己定義的相等。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"\n@Service\npublic class PayService4 implements ApplicationContextAware, InitializingBean {\n private ApplicationContext applicationContext;\n private List payList = null;\n @Override\n public void afterPropertiesSet() throws Exception {\n if (payList == null) {\n payList = new ArrayList<>();\n Map beansOfType = applicationContext.getBeansOfType(IPay.class);\n beansOfType.forEach((key, value) -> payList.add(value)); } } @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext;\n } public void toPay(String code) {\n for (IPay iPay : payList) {\n if (iPay.support(code)) {\n iPay.pay(); } } }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這段代碼中先把實現了IPay接口的支付類實例初始化到一個list集合中,返回在調用支付接口時循環遍歷這個list集合,如果code跟自己定義的一樣,則調用當前的支付類實例的pay方法。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"五、其他的消除if...else的方法"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"當然實際項目開發中使用if...else判斷的場景非常多,上面只是其中幾種場景。下面再列舉一下,其他常見的場景。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"1.根據不同的數字返回不同的字符串"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public String getMessage(int code) {\n if (code == 1) {\n return \"成功\";\n } else if (code == -1) {\n return \"失敗\";\n } else if (code == -2) {\n return \"網絡超時\";\n } else if (code == -3) {\n return \"參數錯誤\";\n } throw new RuntimeException(\"code錯誤\");\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其實,這種判斷沒有必要,用一個枚舉就可以搞定。"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public enum MessageEnum {\n SUCCESS(1, \"成功\"),\n FAIL(-1, \"失敗\"),\n TIME_OUT(-2, \"網絡超時\"),\n PARAM_ERROR(-3, \"參數錯誤\");\n private int code;\n private String message;\n MessageEnum(int code, String message) {\n this.code = code;\n this.message = message;\n } public int getCode() {\n return this.code;\n } public String getMessage() {\n return this.message;\n } public static MessageEnum getMessageEnum(int code) {\n return Arrays.stream(MessageEnum.values()).filter(x -> x.code == code).findFirst().orElse(null);\n }}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"再把調用方法稍微調整一下"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public String getMessage(int code) {\n MessageEnum messageEnum = MessageEnum.getMessageEnum(code); return messageEnum.getMessage();\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"完美。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"2.集合中的判斷"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面的枚舉MessageEnum中的getMessageEnum方法,如果不用java8的語法的話,可能要這樣寫"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public static MessageEnum getMessageEnum(int code) {\n for (MessageEnum messageEnum : MessageEnum.values()) {\n if (code == messageEnum.code) {\n return messageEnum;\n } } return null;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"對於集合中過濾數據,或者查找方法,java8有更簡單的方法消除if...else判斷。"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public static MessageEnum getMessageEnum(int code) {\n return Arrays.stream(MessageEnum.values()).filter(x -> x.code == code).findFirst().orElse(null);\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"3.簡單的判斷"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其實有些簡單的if...else完全沒有必要寫,可以用三目運算符代替,比如這種情況:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public String getMessage2(int code) {\n if(code == 1) {\n return \"成功\";\n } return \"失敗\";\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"改成三目運算符:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"修改之後代碼更簡潔一些。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"4.判斷是否爲null"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"java中自從有了null之後,很多地方都要判斷實例是否爲null,不然可能會出現NPE的異常。"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":" public String getMessage2(int code) {\n return code == 1 ? \"成功\" : \"失敗\";\n } public String getMessage3(int code) {\n Test test = null;\n return test.getMessage2(1);\n }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"這裏如果不判斷異常的話,就會出現NPE異常。我們只能老老實實加上判斷。"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public String getMessage3(int code) {\n Test test = null;\n if (test != null) {\n return test.getMessage2(1);\n } return null;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"有沒有其他更優雅的處理方式呢?"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public String getMessage3(int code) {\n Test test = null;\n Optional testOptional = Optional.of(test); return testOptional.isPresent() ? testOptional.get().getMessage2(1) : null;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"答案是使用Optional"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"當然,還有很多其他的場景可以優化if...else,我再這裏就不一一介紹了,感興趣的朋友可以給我留言,一起探討和研究一下。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章