11
migio
5y

if (condition)
{
one instruction;
}

////////// OR ///////////

if (condition)
one instruction;

Comments
  • 8
    former, with the opening brace a space apart on the line where the condition is
  • 4
    When that second if condition is a return, then sure.

    Otherwise you're going to have to add those braces at some point if the logic or handling to that ever changes.
  • 2
    I think the first one but all on one line is pretty aesthetic, while also not being a bug waiting to happen when extended.

    if(condition) { one instruction; }
  • 0
    @SortOfTested Returning early tho
  • 1
    The second one is fine, I've recently started using it myself.

    Thinking about it, I realized the braces add nothing beyond visual noise for a single statement. I can always add them later when necessary.
    However, you should definitely use an auto-formatter, so an incorrect indentation of a second statement below it doesn't deceive you.
  • 4
    Always use brackets!

    Naming convention and maintainable code is a joke to you?!?
  • 1
    @C0MM1T Thanks, you're asking good questions.

    Conventions are not an end in itself. They are just a means, the end is making the code readable and understandable.

    Braces only add visual noise in this case - they make the code less readable. Thus I prefer to omit them. Short guard statements even go on a single line. That doesn't create more work, but even if so I think it would be worth it.

    I think you should be using auto-formatters anyway. Consistently formatted code is easier to read. I mentioned them here specifically because they will help you catch errors: A second statement after the if() gets dedented - if that's not what you expected, you forgot to add braces. Without auto-formatting you might've missed that. I mean, your automated tests would probably catch it later, but why not add that visual clue right when you're writing the code.
  • 2
  • 1
    @AppleLover No u
  • 1
  • 1
    I love the second one, but be careful at nesting.
  • 0
    TLDR Mostly 1), rarely 2), but they have use cases
  • 0
    @C0MM1T being mindful helps, but since "to err is human" it's not nearly enough. You need to create a safety net for yourself and others.

    In that sense omitting braces is a trade-off. It strengthens your safety net a little with improved readability (YMMV, ofc) but also weakens it a little: You could forget to add them later.

    My safety net consists of many practices. Readability is a big one, as is "making wrong code look wrong" like here (or ideally not even compile). I love rethinking it to get the best possible software quality out of it.
Add Comment