41
davide
8y

I so hate the following statement
if (condition)
makeOperation()

I prefer
if (condition) {
makeOperation()
}

Who is with me?

Comments
  • 20
    What drove me crazy was the missing semicolon. :/
  • 9
    I mostly hate statements like this (with whitespaces at the condition):
    if ( condition ) {
    // code
    }
  • 1
    Needs more semicolon
  • 7
    I can think of three patterns where foregoing curlies ({} brackets) is acceptable. Each one only applies when the block is very simple -- as in a single, very concise, easy-to-read line.

    // multiple (very simple) ifs with (very simple) blocks
    // (e.g. guards, or a series of conditions similar to one another)
    If (x) a;
    If (y) b;
    If (z) c;

    // multiple nested ifs with (very simple) else clauses
    If (x) {
    a;
    If (y) {
    b;
    If (z) {
    c;
    } else w;
    } else v;
    } else u;

    // a one-line block nested several layers deep
    // (I personally dislike this, but find it acceptable)
    If (x) {
    for()
    for()
    a;
    }

    In general, foregoing curlies is only ever acceptable when:
    a) the block is very very simple
    b) doing so improves readability
    c) it's still extremely obvious what the code is doing
    d) you can tell at-a-glance where all the blocks end

    For everything else, use curlies!
  • 0
    @samarthagarwal @gready
    Not in Javascript for example or groovy 😀
  • 1
    Hell no. Clean code ftw
  • 2
    Totally agree with you. If I'd have a penny for every time I fixed my colleagues' missing brackets I'd be quitting my day job by now ;)
  • 0
    condition() && operation()

    ;)
  • 1
    I also hate the liberal use of ternary operators.
  • 0
    With your on this! It's considered a bad practice without the brackets.
  • 1
    It's generally a bad practice (imo) to leave the if without scopes even if syntactically it is ok.

    The main problem is that people sometimes add statements or comment out the statement and then the behavior is not as expected if they forget to scope the if or comment it out.

    The only place when I leave the if without brackets is where the action is when validating I put and throwing exceptions.

    if (string.IsNullOrEmpty(name)) throw new ArgumentException(nameof(name), "should not be null or empty");
  • 0
    @davide it is not about syntax errors, it is about what bothers one programmer and not the other.
  • 2
    Brackets. Always. Period.

    You're not writing code for yourself if you work in a team. In that case remember one important rule: Explicit is better than implicit. Save your teammates a trouble and write clean explicit code. In the end your project and your reputation will benefit from that.
  • 3
    Maybe if this guys used brackets the bug wouldn't appear (if a git merge) or could be spotted easily in code review
    https://google.ie/amp/s/...
Add Comment