if-else 或提前返回 [英] if-else or early return

查看:28
本文介绍了if-else 或提前返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我喜欢使用提前返回语句来防止嵌套 if 语句,我发现这会降低代码的可读性.

Sometimes I like to use early return statements to prevent nesting if statement, which I find makes for less readable code.

我想知道是否有任何客观或压倒性的普遍共识,因为以下两种模式是更好的做法?我不认为这是一个主观问题,因为我真正要问的是有一个近乎客观的偏好.

I am wondering if there is any objective or overwhelming general consensus as two which of the following patterns is better practice? I don't think this is a subjective question, since what I am really asking is there a near objective preference.

void func() {
    if (a) {
        do b
    }    
    else {
        do c
    }
}

void func() {
    if (a) {
        do b
        return;
    }

    do c
}

推荐答案

第一个更好.简而言之,它帮助其他开发人员了解 c 编译是因为条件为假.它还可以防止其他人对您的代码进行破坏性更改.也就是说,它们都是正确的,并且都可以正常工作

The first is better. Simply put,it helps another developer to understand that c compiles because the condition is false. It also prevents other people from making damaging changes to your code. That said,they are both correct and would both work just fine

这篇关于if-else 或提前返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆