What's the purpose of using braces (i.e. {}) for a single-line if or loop?

前端 未结 23 1375
独厮守ぢ
独厮守ぢ 2020-11-28 00:33

I\'m reading some lecture notes of my C++ lecturer and he wrote the following:

  1. Use Indentation // OK
  2. Never rely on operator preced
23条回答
  •  执念已碎
    2020-11-28 01:13

    Another example of adding curly braces. Once I was searching for a bug and found such code:

    void SomeSimpleEventHandler()
    {
        SomeStatementAtTheBeginningNumber1;
        if (conditionX) SomeRegularStatement;
        SomeStatementAtTheBeginningNumber2;
        SomeStatementAtTheBeginningNumber3;
        if (!SomeConditionIsMet()) return;
        OtherwiseSomeAdditionalStatement1;
        OtherwiseSomeAdditionalStatement2;
        OtherwiseSomeAdditionalStatement3;
    }
    

    If you read the method line-by-line you will notice that there is a condition in the method that returns if it's not true. But actually it looks like 100 other simple event handlers that set some variables based on some conditions. And one day the Fast Coder comes in and adds additional variable setting statement at the end of the method:

    {
        ...
        OtherwiseSomeAdditionalStatement3;
        SetAnotherVariableUnconditionnaly;
    }
    

    As a result the SetAnotherVariableUnconditionnaly is executed when the SomeConditionIsMet(), but the fast guy didn't notice it because all lines are almost similar in size and even when the return condition is vertically indented it is not-so noticeable.

    If the conditional return is formatted like this:

    if (!SomeConditionIsMet())
    {
        return;
    }
    

    it is much noticeable and the Fast Coder will find it at a glance.

提交回复
热议问题