2016年10月24日 星期一

小技巧让你的 if else 看起来更漂亮

刚看到一个提问帖: 《如果程序中出现多层嵌套的 if...else...语句,如何重构可使程序逻辑变得更为清晰易读?》,因回答篇幅比较大,单独开个帖子答一下。
个人喜好代码风格不一样,下面只是我认为好的代码风格,不喜勿喷。如果有其他好的技巧,欢迎分享补充。
file

技巧一#

删除 else
如:
function test($arg)
{
    if($arg == 'foobar'){
        return true;
    }else{
        return false;
    }
}
尽量写成这样
function test($arg)
{
    if($arg == 'foobar'){
        return true;
    }

    return false;
}
优先将代码量少,可使流程中断的代码块(return, throw excetion, continue ...)放到 if 中, 提前中断代码。

技巧二#

拆分为多个函数
如果整个 if else 中的代码比较多,或者 if 与 else 中带代码不会导致后面的判断流程中断,并且还有 if else 之外的代码,将就 if else 中的代码拆分为多个函数。
if($age > 18){
    doSomeThingA();
    doSomeThingB();
    doSomeThingC();
}else{
    doSomeThingD();
    doSomeThingE();
}
这种方式需要将函数名取的尽量清晰易懂,不要嫌长。

技巧三#

罗列规则式的写代码
多层 if 嵌套的语法,把他写成线性的,就像写规则一样将其一条条罗列出来
如:
function match($age, $salary, $pretty){
    if($age > 18){
         // do some thing A;
        if($salary > 5000){
            // do some thing B;
            if($pretty == true){
                return true;
            }
        }
    }

    return false;
}
改写成这样是不是清晰多了?
function match($age, $salary, $pretty){
    if($age < 18){
        return false;
    }

    // do some thing A;

    if($salary < 5000){
        return false;
    }

    // do some thing B;

    return $pretty == true;
}

总结#

少用 else , 提前中断(return)!!!#

少用 else , 提前中断(return)!!!#

少用 else , 提前中断(return)!!!#

重要的事情说三遍!

参考资料:#


from : https://laravel-china.org/topics/1263

沒有留言:

wibiya widget