10/8/2015 - 2:24 PM

Comment at end of brace/block?

Comment at end of brace/block?

Java comment at end of brace/block

Is it an accepted practice in the Java programming language to end a brace for a code block with a comment that briefly explains what code block the brace closes off? I personally would think that they are useless comments that clutter the readability of the code, but perhaps I could be wrong. For example:

public void myMethod(int foo) {    
    // some code
    if (foo == 2) {
        for (int i = 0; i < myMax; i++) {
            while (true) {
                // some more code
            } // end while
        } // end for
    } // end if
} // end myMethod(int)

Is the practice of commenting code blocks in a similar manner an accepted practice?

This is not exactly a bad practice, BUT it is a deadly side effect of poor Object-Oriented coding practice!

Also, this violates style guidelines and the tenets of "self-documenting code". You should never have that many brackets or a method long enough to confuse the reader about bracket placement, instead encapsulate that functionality in another method that is well documented.

Brackets imply either looping or complex if-else logic chains, good programming practice is to have a method do exactly one thing and do it well, then build your program from these smaller, atomized methods. I would read Butler Lampson's seminal piece "Hints for Computer System Design". It goes into some of the details on how to design good software.

So essentially, don't comment like this because:

  1. It violates style guidelines
  2. It shows poor Object-Oriented programming - atomize your functionality!
  3. It is a deadly side effect of coding practice which goes against the underlying concepts of why Java was created - encapsulation, specifically information hiding
  4. It violates the concept of self-documenting code
  5. Other programmers will make fun of you.