do{}while(false):
在工作中我们能经常发现有人写 do{}while(false) 这样的代码,初看时让人迷惑不解,按照上面的语法 do{}while(false) 这样 do{} 里面的代码只会执行一次的啊,那么问题来了,为什么要这样写?
试想,我们在工作中是不是经常会遇到一种情况:第二个判断需要依赖第一个判断的结果,甚至第三个判断需要依赖第二个判断的结果。如下样式的代码:
if (one == true) { if (two == true) { if (three == true) { //第三个依赖第二个判断结果,第二个依赖第一个判断结果。 //... } } }
那这样的代码是不是看起来好恶心,各种判断嵌套在一起,很是不容易理清代码逻辑,而且很容易出错。那有没有一种清爽的代码风格来解决这个问题呢?答案肯定是有的,就是我们上面提到 do{}while(false) 。
那要如何用代码实现呢,请看下面的代码示例:
do { if (one == false) { break; } if (two == false) { break; } if (three == false) { break; } } while (false);
既然后面的判断依赖前面的判断结果,那么所有的条件都去判断是否等于false,等于false的直接break跳出do while 循环。这样的代码风格是不是比刚才那种写法清爽多了。
结论:
do{}while(false) 最大意义是:简化 if else 的嵌套结构判断逻辑。