search

Home  >  Q&A  >  body text

我代码比较不会写,if语句嵌套太多,不好维护

大家平时代码是怎么写的,如何竟可能的减少if语句的嵌套,让代码更好维护

代言代言2916 days ago881

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-02-27 15:32:55

    我一直提倡:

    好的习惯例如异常情况等提前return掉

    例如,
    
    一般写法:
    function demo()
    {
        if(...) {
            //....
        }else {
            // ...
        }
        return ...
    }
    
    提前return写法:
    function demo()
    {
        if(...) {
            return ...
        }
        return ...
    }

    其次,使用异常,使用try...catch...捕获,

    class Demo
    {
        public function test()
        {
            if(...) {
                throw Exception('message', 'code');
            }
            //code...
        }
    }
    
    try {
        //code...
        $demo = new Demo();
        $demo->test();
    }catch(Exception $e) {
        //code...
    }


    reply
    0
  • Cancelreply