if ((condition1 && condition2 ) || ((condition2 || condition3) && condition4)) { }
问题解决:分解条件表达式,分解成多个独立的函数,为分解的新函进行良好的命名,从而更清楚表达本身意图。缓存
if (date.before(SUMMER_START) || date.after(SUMMER_END)) { } // 优化后 if (notSummer(date)) { }
public void workOrRest { if (isWorkDay()) { System.out.println("sad,is work day!!!"); } else { if (isWorkTime()) { System.out.println("shit,is work time!!!"); } else { rest(); System.out.println("happy happy happy!!!"); } } }
解决办法:经过卫语句,有时候条件式可能出如今嵌套n次才能真正执行,其余分支只是简单报错返回的状况,对于这种状况,应该单独检查报错返回的分支,当条件为真时当即返回,这样的单独检查就是卫语句(guard clauses).卫语句能够把咱们的视线从异常处理中解放出来,集中精力到正常处理的代码中。app
public void workOrRest { if (isWorkDay()) { System.out.println("sad,is work day!!!"); return; } if (isWorkTime()) { System.out.println("shit,is work time!!!"); return; } rest(); System.out.println("happy happy happy!!!"); }
if (houseName.equals("Targaryen")) { ... System.out.println("Blood and fire"); } else if (houseName.equals("Baratheon")) { ... System.out.println("Ours is the Fury"); } else if (houseName.equals("Stark")) { ... System.out.println("Winter is coming"); } else if (houseName.equals("Lannister")) { ... System.out.println("Hear Me Roar"); } else if (houseName.equals("Arryn")) { ... System.out.println("as High as Honor"); } else if (houseName.equals("Tyrell")) { ... System.out.println("Growing Strong"); } else if (houseName.equals("Tully")) { ... System.out.println("Family, Duty, Honor"); } else if (houseName.equals("Martell")) { ... System.out.println("Unbent, Unbowed, Unbroken"); } else if (houseName.equals("Greyjoy")) { ... System.out.println("We Do Not Sow"); } else { ... System.out.println("world peace"); }
问题解决:利用策略or状态模式,消除业务判断,各之类分别关注本身的实现,大大下降了系统各部分之间的依赖。利用Map缓存分支状态信息。基本能够达到对修改封闭,对扩展开放。函数
<property name="thronesMap"> <map> <entry key="Targaryen"><bean class="game.of.thrones.TargaryenStrategy"/></entry> <entry key="Baratheon"><bean class="game.of.thrones.BaratheonStrategy"/></entry> <entry key="Stark"><bean class="game.of.thrones.StarkStrategy"/></entry> <entry key="Lannister"><bean class="game.of.thrones.LannisterStrategy"/></entry> <entry key="Arryn"><bean class="game.of.thrones.ArrynStrategy"/></entry> <entry key="Tyrell"><bean class="game.of.thrones.TyrellStrategy"/></entry> <entry key="Tully"><bean class="game.of.thrones.TullyStrategy"/></entry> <entry key="Martell"><bean class="game.of.thrones.MartellStrategy"/></entry> <entry key="Greyjoy"><bean class="game.of.thrones.GreyjoyStrategy"/></entry> <entry key="Default"><bean class="game.of.thrones.DefaultStrategy"/></entry> </map> </property> public interface GameOfThronesStrategyService { /** * 具体实现处理 */ void mainTitle(); } thronesMap.get(houseName).mainTitle();