if ($user != null) { if (time() >= strtotime('12 pm')) { if ($user->hasAccess(UserType.PREMIUM)) { if ($store->hasItemsInStock()) { // the content a premium user user should be able to see when the store is in stock // after 12pm. } else { return'We are completely sold out.'; } } else { return'You do not have premium access to our website.'; } } else { return'This section is not opened before 12PM'; } } else { return'You are not signed in.'; }
改写成这种:
1 2 3 4 5 6 7 8 9 10
if (condition1()) { return ...; }
if (condition2()) { return ...; }
// Input is valid. doSomething();
在《阿里巴巴 Java 开发手册(华山版)》的第一章《编程规约》也有提到:
【推荐】表达异常的分支时,少用if-else方式,这种方式可以改写成:
1 2 3 4 5
if (condition) { ... return obj; } // 接着写else的业务逻辑代码;