卫语句 Guard Clause 是一种编程模式用于在函数或方法开始时检查前置条件,如果条件不满足就提前返回或抛出异常。
可以使代码更清晰、减少嵌套层次,并提高可读性。
传统嵌套示例:
function getEmployeeSalary(employee) {
if (employee != null){
if (employee.department != null) {
if (employee.department.financeRecords != null) {
return employee.department.financeRecords.salary;
}
}
}
return 0;
}
使用卫语句:
function getEmployeeSalary(employee) {
if (employee == null) return 0;
if (employee.department == null) return 0;
if (employee.department.financeRecords == null) return 0;
return employee.department.financeRecords.salary;
}
2747

被折叠的 条评论
为什么被折叠?



