减少函数return的一个实例

SonarLint提示:

Functions should not contain too many return statements

Having too many return statements in a function increases the function’s essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.

意思就是,如果函数的return语句多,会使得函数的逻辑难以阅读和理解。

 

 

 

 /**
  * 改造前的代码
  *
  * 
  */
public function verifyValuePwd($password)
 {
        // 密码最小长度
        $password_len = mb_strlen(trim($password));
        if ($password_len == 0) {
            return array(-1,'密码不能为空');          
        }
        if (6 > $password_len) {
            return array(-2,'密码不能少于6位');            
        }
        if ($password_len>20) {
            return array(-2,'密码不能大于20位');            
        }

         /**
          * 此处还有若干代码
          * 
          */
        if ($i >= 2) {
            return array(0,'');
        }else{
            return array(-4,'密码至少包含大小写字母,数字,输入特殊字符2种组合');
        }

}


 /**
  * 改造后的代码
  *
  * 
  */
public function verifyValuePwd($password)
 {
        // 密码最小长度
        $password_len = mb_strlen(trim($password));
        if ($password_len == 0) {
            throw new \think\Exception('密码不能为空', -1);
        }
        if (6 > $password_len) {
            throw new \think\Exception('密码不能少于6位', -2);            
        }
        if ($password_len>20) {
            throw new \think\Exception('密码不能大于20位', -2);            
        }

         /**
          * 此处还有若干代码
          * 
          */
        return $i >= 2 ? [0, ''] : [-4, self::PWD_ERR];

}

从这里就能看出抛出异常的优势了。当程序运行结果不符合功能预期,则完全可以抛出异常,而不是返回错误码。这个函数的功能是验证密码,期望的结果是密码符合业务预定义规则,即为验证通过。若验证不通过,则均属于异常结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值