10 Best Practices for Code Commenting & Formatting
Join the DZone community and get the full member experience.
Join For FreeCode commenting and formatting is all about code understandability. Code understandability is very relevant to code maintainability. So, small details about programming may help maintainability. In this context, some practices about commenting and formatting will be told here:
Commenting
- Use comments "as required".
- Unnecessary over-commenting in each line will reduce readability:
- int count = 0; // assigning zero as initial value to the count (?!?)
- Lack of commenting will increase maintenance time. Also, variable/method names should be understandable and self commenting
- int s = sqrt(v1) + v2 / v3 + fread(s). getChar(0) //(?!?)
- List<int> getVal(int val, int len, String op) //(?!?)
- Unnecessary over-commenting in each line will reduce readability:
- Don't write uncorrect comments. Uncorrect explanations are worse than no-comment.
- Write comments for variables which are important and non-selfdocumenting.
- Writing comments (e.g. JavaDoc declaration) for all public methods is a good practice. Of course, these comments should be "really necessary" and "as required".
- Document "gotcha"s and "todo"s instantly when detected. These items may be remembered for that day but may not for tomorrow when not documented, so a buggy code will be inevitable.
Formatting
- Use brackets consistently. You may choose opening a bracket at the end of the current line or at the beginnning of the new line. Choose one of them and use consistently in the whole application.
- Use blank lines consistently and as required. Blank lines may be used for separating code lines or line groups semantically for readability. E.g. 3 blank lines at the end of a method, no-blanks on whole code or one or two blank lines between each line of code reduces readability and not good for eye pleasure.
- Pay attention for indentation. Correct indentation for grouping statements is as important as using brackets and blank lines.
- Character count of a line should be limited for readability. This limit is generally 80 for most developers, but may change a little due to some other development parameters.
- Using space chars in code should also be consistent in whole application. Generally, situations below are suitable for using spaces:
- Between operators and operands:
- a += b , c = 0; (a == b)
- Between statement keywords and brackets:
- if (value) {, public class A {
- After ';' char in loops:
- for (int i = 0; i < length; i++)
- Between type casters and operands:
- (int) value , (String) value
- Between operators and operands:
Published at DZone with permission of Cagdas Basaraner, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments