dpg76975 2013-05-27 11:34
浏览 24

块格式的代码标准

There are two primary ways to format blocks of code.

I'm used to doing stuff like so:

function do_something() {
    if(cond) {
        if (cond 2) {
            if (cond 3) {
                whatever_good();
            } else
                whatever_bad3();
        } else
            whatever_bad2();
    } else
        whatever_bad1();
}

But recently I was introduced to this type of organising code:

function do_something() {
    if(!cond) {
        whatever_bad1();
        return;
    }
    if (!cond 2) {
        whatever_bad2();
        return;
    }
    if (!cond 3) {
        whatever_bad3();
        return;
    }

    whatever_good();
}

This second way is more readable, I have to admin. But it just makes me cringe to write code like that... Even tho I realise that the second if probably better. I think I just have to change my habits.

So. My question is: Is there some guidelines on how to structure code in a better way? This may be too broad, but this is something that you can't find easily in google. Especially this particular case for these two ways of writing code. I tried to find comparison of these two ways, but couldn't find even a single article about it. Also maybe some guidelines on improving readability.

So, I would really appreciate some links.

PS - Right now I'm asking this for php, but I think this also works for most other languages. So, this does not have to be necesary sticktly about php.

  • 写回答

1条回答 默认 最新

  • douleng0794 2013-05-27 11:37
    关注

    How about this?

    if(cond1 && cond2 && cond 3) {
        something_good();
    }
    else {
        something_bad();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100