编码标准/编码C ++中的最佳实践 [英] Coding Standards / Coding Best practices in C++

查看:102
本文介绍了编码标准/编码C ++中的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


考虑下面的两个代码段。
哪一个更好,为什么?如果你
有任何其他想法,请做
提及。在哪里可以找到这样的
编码实践的答案?如果你
知道任何书/文章,
请分享。

Consider the two code segments below. Which one is better and Why? If you have any other idea, please do mention. Where can I find answers to coding practices like these? If you are aware of any book / article, please do share.

//代码1

bool MyApplication::ReportGenerator::GenerateReport(){
    bool retval = false;
    do{
        if (!isAdmin()){
            break;
        }
        if (!isConditionOne()){
            break;
        }
        if (!isConditionTwo()){
            break;
        }
        if (!isConditionThree()){
            break;
        }

        retval = generateReport();
    } while(0);
    return retval;
}

// Code2
$ b

//Code2

bool MyApplication::ReportGenerator::GenerateReport(){
    if (!isAdmin()  || !isConditionOne() || !isConditionTwo() || !isConditionThree()){
        return false;
    }
    return generateReport();
}

Robert C. Martin的干净的代码是一本很好的书, 。但是,我想这本书倾向于Java。

The clean code by Robert C. Martin is a nice book which deals with this. But, I guess that book is inclined towards Java.

更新:


  1. 有意使用do {} while(0);

  1. I have purposefully used do{ }while(0); loop as I did not wanted to use goto.

我想摆脱这么多if和break语句,所以我提出了代码2.

I wanted to get rid of so many if and break statements, so I proposed Code 2.

我可以从回复中看到的是Code1和Code2的混合响应。有些人喜欢goto,相比代码1(我认为更好)。

What I can see from the replies is a mixed set of responses for both the Code1 and Code2. There are people who prefer goto as well compared to Code 1 (which I thought was better).

推荐答案

我真的不喜欢使用do / while循环。另一种方法是将你在Code2中的条件转换为单独的if检查。这些有时被称为保护子句。

I don't really like using a do/while loop in this way. One other way to do this would be to break your conditional in Code2 into separate if checks. These are sometimes referred to as "guard clauses."

bool MyApplication::ReportGenerator::GenerateReport()
{
    if (!isAdmin())
        return false;

    if (!isConditionOne())
        return false;

    // etc.

    return generateReport();

}

这篇关于编码标准/编码C ++中的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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