Search code examples
c++curly-bracesbraces

Fixing braces (brace matching) tool


I just finished writing thousands of lines of robotics code that has logic statements upon logic statements upon logic statements just to find out from my compiler that I am missing a brace somewhere.

Is there a tool that can automatically search code and fix unmatched braces?


Solution

  • Every better text editor will highlight unmatched braces. However automatically fixing braces? No, because that would take magical divination. Take this expression for example

    x = (3 + y * 5 - 4 * 7
    

    Where would you put the brace? Is it

    x = (3 + y) * 5 - 4 * 7
    

    or is it

    x = (3 + y * 5 - 4) * 7
    

    Those two are very different expressions.


    But seriously, you wrote thousands of lines of code without testing in between? The right approach on any kind of project is to break it down into small, independently written and testable units. I'm not just talking about separating code in functions. I'm also talking about separating code in multiple, independent compilation units (source files).

    As a rule of thumb your typical single source file should be no longer than 2000 lines of code. If it's longer, you did something wrong. Similar single functions should not be longer than one small screen full (about 50 lines).

    You write the outline of one such unit, and test it. How do you test it? By writing some test suite that utilizes the unit in the simple most way. Test each unit independently. You test units… hence this is called unit tests. Note that unit tests don't validate code, they only show that the code adheres to expected behavior for the chosen test conditions.

    Once your unit test framework for the outline, you can flesh it out. For each new feature you add to the unit you add a complementing test case to the unit test.