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?
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.
In Java there are three types of comments:Single-line comments. Multi-line comments. Documentation comments.
My take on it is that as a rule it is NOT a good practice. As always with rules there could be exceptions but very rare.
It is not a good practice because
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With