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