Friday 18 August 2017

Java Coding Guidelines And Best Practices For Error-Free Code part 2 ~ foundjava

1.3.2.8- Member Function.
Have a function name that relates to the task it meant for. Start it with an active verb whenever possible.
Some good naming practices.
Good method names.
showStatus(), drawCircle(), addLayoutComponent().
Bad method names.
menuButton() – noun phrase; doesn’t describe function.
OpenTab() – starts with upper-case letter.
click_first_menu() – uses underscores.
Boolean getter member functions.
It’s a good practice to prefix boolean getter functions with <is>.
e.g. isVisible(), isChecked(), isNumeric().
Getter member functions.
Usually all getter functions should start with <get> prefix.
e.g. getLocalDate(), getMonth(), getDayOfMonth().
Setter member functions.
Usually all setter functions should start with <set> prefix.
e.g. setLocalDate(), setMonth(), setDayOfMonth().
Note: Getter/Setter functions should follow a strict guideline for Java Bean classes.

1.4- Source Code Style Guidelines.

1.4.1- Line Spacing.

1- Limit each line under 80 characters.
2- Limit comment length up to 70 characters.
3- Keep tab sizes equal to 4 spaces.

1.4.2- Blank Space.

Allow one space between operators and expressions.

1.4.3- If/Else.

If statement must adhere to the following format.

1.4.4- For.

A for statement must adhere to the following format.
In JDK 1.5 release, there is a new feature introduced related to enhanced for loop. In this, the array index is not necessary for the retrieval of an array element.

1.4.5- While.

A while loop must adhere to the following format.

1.4.6- Do..While.

A do-while loop must adhere to the following format.

1.4.7- Switch.

A switch statement must adhere to the following format.

1.4.8- Try/Catch/Finally.

The try/catch statement must adhere to the following format.
A try-catch statement may also be followed by finally, which executes regardless of the execution status.

1.5- Comments.

Here are the Java coding guidelines for quality commenting.
1- Use comments before the declarations of interfaces, classes, member functions, and fields. Adopt Javadoc format for commenting.
2- Apply C-style comments to outline code that is no longer applicable.
3- Limit comments to a single line for member functions, sections of code, and declarations of temporary variables.
4- Write comments to improve the clarity and readability of the code.
5- Don’t add duplicate information while giving comments.
6- Limit the Comment length up to 70 characters per line.
In Java, there are four ways of adding comments.

1.5.1- Block Comments.

All data structures, algorithms within the function can be explained through block comments. Block comments should be indented to the same level as the code.

1.5.2- Trailing Comments.

Mostly used to describe the small size code like conditions. Make sure the comment should be short as well.

1.5.3- Single Line Comments.

Use such comments within the member functions to document logic, sections of code, and declarations of temporary variables. Also, this comment can be used to indicate the end of iterative statements when it is nested.

1.5.4- Documentation Comments.

1- Documentation comments describe Java Classes, Interfaces, Constructors, Methods, and Fields.
2- This type of comments should appear before declarations.
3- Make sure that these comments are not inside a method or constructor block.
4- Documentation comments start with  /** and ends with  */.
5- JavaDoc processes documentation comments.

1.6- Standard Java Coding Conventions.

1.6.1- Declarations.

1- Limit one declaration per line for objects and variables.
2- Avoid declaring different types of the same line.
3- Set default values for local variables at the time of declaration.
4- Best to have all declarations at the outset of the block.
5- Don’t use declarations that override other variables having identical names.
6- Make sure to eliminate warnings if there is any.

1.6.2- Statements.

1- Write only one statement per line.
2- Don’t initialize more than three variables with a comma inside a “for” loop.
3- Don’t forget to end a switch-case with a break statement.
4- Make sure the switch statement must have a default case.
5- Do not hard-wire any number in the code instead, use a Macro to define constants.
6- While comparing always keep the constant on the left-hand side to avoid any unpredictable assignments.
7- While returning from a function, follow the single and single exit approach.
8- Make it a practice to check for null while accessing any object or data structure.
9- Limit the no. of arguments to five for functions and methods.
10- Also, don’t extend the no. of characters from 80 characters per line.

1.6.3- Import Declaration.

1- Begin an import statement starting from the first column and use a single space to separate the <import> keyword from the package name.
2- Group all import statements using the package name.
3- Use a blank line to separate groups of import statements.
4- Sort the import statements as per the dictionary order.
5- Prevent from using an open import statement like <import java.io.*;> as it’ll lead to unused imports.

1.6.4- Blank Spaces.

1.6.4.1- Adopt Blank Space Reject Tabs.
1- Always set a single blank space to use in the editor. Using tabs isn’t wise as the tab size varies editor by editor.
2- Add a single space between a keyword and the opening parenthesis. This applies to keywords like the <catch, for, if, switch, synchronized, and while>. Don’t do this for <super and this>.
3- Add a space after the comma in a list and after the semicolons inside a “for” loop.
1.6.4.2- Avoid Using Blanks.
1- Between a function name and its opening parenthesis.
2- Before or after a .(dot) operator.
3- Between a unary operator and its operand.
4- Between a cast and the expression.
5- After an opening parenthesis or before a closing parenthesis.
6- After an opening square bracket “[” or before a closing square bracket “]”.
7- Do not use special characters like form-feeds or backspaces.

1.6.5- Indentation.

Line indentation is always 4 spaces for all the indentation levels. You may indent using tabs (which you should avoid) as to reduce the file size. However, you shouldn’t alter the hard tab settings to accomplish this. They must be set to eight spaces.

1.6.6- Continuation Lines.

Lines should be limited to 80 columns except for non-ASCII encoding. If they go more than 80 chars, then split them into one or more continuation lines. All the continuation lines should be aligned and indented from the first line of the statement. The amount of the indentation depends on the type of statement. The same indentation rule you should follow for the nested blocks like <try…catch>, <switch…case> or loops. See the below examples.

1.6.7- Member Documentation Comments.

1- All public members must be preceded by a documentation comment.
2- Programmer can choose to add a description for protected and default access members.
3- Private units don’t need a documentation comment.
4- The fields that don’t have a documentation comment should have single-line comments describing them.

1.6.8- Class And Instance Variable Field Declarations.

1- Variables defined using the keyword static are class variables.
2- Variables defined without the “static” keyword are instance variables.
3- You should declare a class variable first if there is any.
4- Next, you should declare instance variable after the class variable.
A field declaration looks like the following. Elements in square brackets “[]” are optional.
The <FieldModifiers> can be any valid combination of the following keywords, in this order:
Place all the field declarations on separate lines. Don’t club them with each other in a single line.

1.7- Exception Handling.

You must follow the below Java coding guidelines for implementing effective exception handling.
1- Always write a catch block for handling exceptions.
2- Make sure to add a logging message or the stack trace in the catch block.
3- Avoid catching the general exception and have the specific exception.
4- The cleanup code should be added in the <finally> block.
5- This provides a single location for the cleanup and it’s guaranteed to run.

1.8- Eclipse Plugins For Code Styling.

To implement Java coding guidelines, you need several tools. And it’s easy to integrate these with Eclipse IDE. Some of them we’ve listed down below.
1- Checkstyle plugin.
2- Spell checker plug-in tool.
3- Find bugs plugin.
4- Code profiler tool – to detect the guidelines violation.
5- TestNG or JUnit for unit testing.
6- ANT/Maven for building the project.

Final Thought.

We tried to cover the most common Java coding guidelines that we thought could be useful for both the Java developers and automation testers. In case, there is something you would like to add/update to this post, please don’t hesitate to share with us.
Our readers often give their valuable suggestions which we promptly bring through new posts on this blog. Please remember that your interest drives us to deliver better content.

No comments:

Post a Comment