java coding standards and best practices (2)

1.1 java coding standards and best practices Module Organization

The term module in this context refers to a source file. A source file should contain one public class; it may contain additional non-public classes. So java coding standards is basically refer to java source files. When coding source file is our best practices time(Best practice is to use only one class definition per module.)

The elements of a standards module should be in the following order:

Package name

Import section

Class definition

Class header

Constants (final class variables): public, protected, private

Class variables (private only)

Fields (instance variables) (private only)

Constructors

Other methods.

When ordering java methods, static should be first, public second, protected third.

Java coding standards require you Keep related methods together

When overriding Java superclass functions, keep them in the same order as in the superclass, and preferably together.

Protected inner classes, static or otherwise

Private inner classes, static or otherwise

See also the section on Javadoc comments.

1.2 Standards Module Header

The module header consists of the package name and the import section. With these in place, we can see at a glance what this file is about:

****REVIST, make standard header info.
/**
*
* detailed description of the method
* @param aParam1 – desription of the parameter
* @param aParam2 – desription of the parameter
*
* @return description of the return value
* @exception anException1 – description of the exception
* @exception anException2 – description of the exception
*
* @see some other method or class
* @see some other method or class
*/

In the import section, list each imported module explicitly. The coding standards listing each imported is more readable.

Best practices Example:

Standard Non-Standard
import javax.servlet.RequestDispatcher;import javax.servlet.http.HttpSession;import com.orionauto.autolink.businessobjects.Driver; import javax.servlet.*;import javax.servlet.http.*;import com.orionauto.autolink.businessobjects.*;

Neither of these conventions is consistently maintainable; so don’t put a lot of work into verifying that all listed modules are used. Likewise, don’t spend time converting existing modules from one format to the other.

1.3 Code Layout

A good layout strategy should accurately and consistently represent the logical structure of the code, it should make the code readable, and it should be easy to maintain. This is standards java coding give you advantage. The rules in this section are designed to meet those criteria and best practices.

1.3.1 Class Headers

Write class headers on a single line if there is room for it.

If not, break the line before extends and implements. Indent succeeding lines.

If the class header is on a single line, put the opening brace at the end of that line.

If the class header needs multiple lines, put the opening brace left aligned on a line by itself.

1.3.2 Method Headers

Write method headers on a single line if there is room for it.

If not, break the line immediately after the opening parenthesis. This leaves all the parameters on the same line.

If there still isn’t enough room, put each parameter on its own line.

If the method header is on a single line, put the opening brace at the end of that line.

If the method header needs multiple lines, put the opening brace left aligned on a line by itself.

1.3.3 Indentation

Standard coding indentation should be 4 spaces. Actually, indentation is one tab, which should be set to display as four spaces.

Use tabs for indentation only. Any white space after the indentation level should be actual spaces, so that the formatting will be reasonable no matter how many spaces a tab equals.

1.3.4 White Space in the Code

White spaces in general enhance readability.

Add one space in the following places:

Between operators

After comma in method declarations and invocations

After semicolons in for-loops

Before and after the assignment operator

No space in the following places:

o Between a method name and the opening parenthesis

o Around opening and closing parentheses in a function declaration or invocation

o Around opening and closing square brackets in an array declaration or reference

Best practices Example:

if (!comboValid)
{
this.accounts.removeAll();
for (int i = 0; i < accountList.size(); ++ i){this.accounts.addItem(accountList.get(i).toString())}

final String accountID = ContextManager.query(SOME_ID);

int index = this.getGroupIDIndex(accountID);

this.accounts.select(Math.max(0, index));

this.comboValid = true;

}

private String titles[] = null; // array of strings

client.height =

size.height – this.insets.top – this.insets.bottom –

this.title.height;

public String getItem(int aRow, int aColumn) {

return (String) this.list[aColumn].elementAt(aRow);

}

1.3.5 Braces and Line Breaks

Always use (curly) braces, even for blocks with only one statement. This removes one common source of bugs and eases maintenance:

1. You can insert or remove statements within a block without worrying about adding or removing braces

2. You never have a problem matching else clauses to if clauses.

Best practices Example:

Standard Nonstandard
if (bottom < index){
this.topRow = index – this.rows;
}else if (index < this.topRow){
this.topRow = index;
}
if (bottom < index)
this.topRow = index – this.rows;
else if (index < this.topRow){
this.topRow = index;
}

This rule applies to the following constructs:

for, while and do-while loops

if-else statements

try, catch and finally clauses

synchronized blocks.

Note that the opening brace is at the end of the first line, even for class and method definitions. The only exception is if the expression needs to be broken; in that case, readability is best served by putting the opening brace on the next line.

1.3.6 coding standards Line Lengths and Line Breaks

One statement per line.

Try to keep line lengths below 80 characters. This rule is not absolute; it is better to have a 90-character line than to break a statement.

If you must break a line, indent the continuation line(s).

If you must break a line, make it obvious by ending the first line with something that needs a continuation:

1. Break assignments after the assignment operator.

2. Break arithmetic and logical expressions after an operator.

3. Break the line to emphasize major sub-expressions.

4. Break method invocations after the opening parenthesis. If the parameter list still won’t fit, break between each parameter or between each logical group of parameters if this seems better.

5. Break method declarations the same way, and put the opening brace on the next line, unindented.

6. If you need to break conditional expressions (e.g., in if or while-statements), follow rules 1 and 2 above, and put the opening brace on the next line, unindented.

Using extra variables top hold partial (intermediate) expressions can help you avoid line breaks and at the same time improve readability by making the code self-documenting. This is a judgment call; the following example goes too far, perhaps, but does at least illustrate the point:

Best practices Example:

Standard
if (clickTime – this.previousClick < DOUBLECLICK_TIME&& this.selection == rowClicked)
{

}
Original Code
if ((clickTime – this.previiousClick)<(DOUBLECLICK_TIME)&&(this.selection == rowClicked))

1.3.7 standard Switch/case Layout

Indent the case clauses respect to the switch statement.

Indent the statements that belong to a switch, one statement to a line.

In the case of large, repetitive lists of cases, it may be better to do a table layout as follows:

Note: Best practice to use break statements for each case. If you are not using breaks, for fall through logic, clearly comment the code. Always include a default statement.

Best practices Example:

switch (some_value)
{
case case1:
bla_bla[0] = value1;break;

case case2:

bla_bla[0] = value2;

break;

default:

bla_bla[0] = value0;

}

This is our first part of java coding standards and best practices. you can read the previous about why we need Java coding standards

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *

*

code

  1. jolin

    nice articles, this is very useful for a java developer, thank you share it

    Ответить