Professional Documents
Culture Documents
S.No. 1 2 3 4 5
Page 1
Style
S.No. 01 02 03 04 05 06 07 08 09 10 Rule Maximum number of lines a class can contain Maximum number of methods a class can contain Number of static fields in a class. Number of non-static fields in a class. Maximum number of lines a method can contain Maximum number of methods that can be called from a class Nested depth The number of classes a file can contain. Number of local valiables in a method. Indendation Maximum 1000 20 14 20 150 200 5 5 200 4 character byte
11
Space
12
Line
Page 2
Style
Description
This rule checks whether the nested depth of branching statements (if, for, while, dowhile, switch, and catch blocks) exceeds 5
(1) After the comma in the row of an argument. (2) Between the ". (dot)" operator, the operator except a unary operator, and its operand. (3) Between two or more [ in the small parenthesis of an and sentence or or sentence ]. (4) After a cast operator. (5) After thethe semicolon in elements a for sentence. 1. Between following which constitute a source file Header comment Package declaration Import declaration Definition of a class/Interface 2. Between methods (however, when meaningful as a series of blocks, such as between setter/getter and a method group which carried out the overload, it is not necessary to put the blank line) 3. Between the logical blocks in a method . 4. In addition, a part required for the improvement in readability.
Page 3
Naming_Convention
S.No. 1 2 3 Category Package Interaface Class Rule Package name must be in lowercase First letter of an interface has to be I First word in the class name should be a noun , starts with capital letter and meaningful
Method
First word in the method name should be a verb and starts with small letter,the subsequent words of method name begin with capital letter.
Variable
a camelCase
Reference
http://www.appperfect.com/support/java-codingrules/namingconvention.html
Page 4
Naming_Convention
Best practice jp.co.hitachi.jkk.sampleproject.logic; IdownloadHistory public MyClass Methods have to be named appropriately. To get the downloaded history, the method could be named as
getDownloadedHistory() To insert the downloaded history to db, the method name could be insertDownloadedHistory() To update user profile, the method could be named as updateUserProfile() To delete an user profile, the method could be named as
DEFAULT_LIST_SIZE
Page 5
Naming_Convention
Should Avoid
Page 6
Coding_Rule
S.No. Rule
Exception, Throwable, RuntimeException, and other exceptions are superclasses of other exceptions. Catching such an exception may lead to catching an unintended exception and to incorrect exception handling. Known null value in conditional statement
A parameter includes a conditional operator whose operands are of different numeric value types.
Page 1
Coding_Rule
A NullPointerException is caught.
The return value of a file operation method of the java.io.File class is not referenced.
Page 2
Coding_Rule
There is a "case" label in which processing falls through to the next label in a "switch" statement.
System.(out|err).(print|println) is used.
Throwable#printStackTrace is used.
Page 3
Coding_Rule
Unused instance
There is a method that has the same signature as a superclass "private" method.
Page 4
Coding_Rule
A class type with a visibility lower than "protected" is used for a "protected" field.
A class type with a visibility lower than "protected" is used for the parameter or return value of a "protected" method
Page 5
Coding_Rule
Class cyclometry complexity should not exceed Method/Constructor cyclomatic complexity should not exceed Depth of class inheritances It is recommended that a collection class field which is defined in a class is private final. When comparing "elements" of arrays, java.util.Arrays.equals() must be used.
Page 6
Coding_Rule
Page 7
Coding_Rule
Page 8
Coding_Rule
Page 9
Coding_Rule
Example
import java.util.*;
public class MyClass { public boolean isMatch(String name) { return name.equals("MyClass"); } public String getName() { return "MyClass"; } } try { num = Integer.parseInt(data.nums[index]); } catch (Exception e) { System.out.println("A non-numeric value has been specified."); } String str; ... if (str == null && str.length() == 0) { ... if (str != null || str.length() > 0) { public class MyClass { public MyClass() { method((flag) ? 1 : 1.5f); } // This is not executed regardless of the value of "flag". private void method(int n) { ... } // This is executed regardless of the value of "flag". private void method(float f) { ... } } try { data = text.getBytes("UTF-8"); ... } catch (UnsupportedEncodingException e) { // This exception can never occur. }
Page 10
Coding_Rule
try { ... } catch (IOException e) { ... } finally { // TODO: Release processing should be implemented here. } if (arg != null) { ... } else { // TODO: Error handling should be coded here. } String str; ... if(str.equals(null)) { ... } class MyClass { Private String str; MyClass() { } } public String getFileName(String key) { try { File file = fileManager.getFile(key); return file.getName(); } catch (NullPointerException e) { return null; } }
Page 11
Coding_Rule
boolean check(String str) { if (str == "abc") { .... } else if (str != "xyz") { .... } else { .... } } switch (i) { case 1:
case2: // Not executed if i == 2. ... break; default: }
switch (num) { case 1: System.out.println("one"); // Since "break" is not written, control moves to the next label. case 2: System.out.println("two"); break; case 3: System.out.println("three"); break; switch (arg) { case 1: ... break; case 2: ... break; } class Foo{ public void doSomething () { System.out.println("BEGIN of doSomething"); ... } } class Foo{ public void doSomething () { try { ... } catch (IOException ioe) { ioe.printStackTrace(); } } }
Page 12
Coding_Rule
for (int i = 0; i < list.size(); i++) { Foo foo = new Foo(); foo = (Foo)list.get(i); ... } public void test(char ch){ // Character.isSpace(char) method is deprecated. if(Character.isSpace(ch)){ ... boolean compare(Integer integer1, Integer integer2) {
return integer1 == integer2: }
public class SuperClass { private void method() { ... } } public class SubClass extends SuperClass {
private void method() { ... }
Page 13
Coding_Rule
public class SuperClass { static void method1() { ... } void method2() { ... } ... } public class SubClass extends SuperClass {
static void method1() { // Hides the method. ... } void method2() { // Overrides the method. ... } ... public static void main(String[] args) { SuperClass sup = new SubClass(); SubClass sub = new SubClass(); sup.method1(); // Invokes method() of SuperClass. sub.method1(); // Invokes method() of SubClass. sup.method2(); // Invokes method() of SubClass. sub.method2(); // Invokes method() of SubClass. private int count = 0; public void myMethod() { count = 0; for(int i = 0;... ) { count++; ... } } } public class MyClass { private void aMethod() { ... } private void bMethod() { ... } void cMethod() { bMethod(); } }
class MyClass {
Page 14
Coding_Rule
public class MyClass {
public ListImpl list; ... private class ListImpl implements List { ... } } class SuperClass {
public class MyClass { private String name; public void setName(String name) {
if (name == null) { // "this" is omitted. this.name = name; } } }
50 15 5 public class MyClass { public Map<String, Integer> map = new HashMap<String, Integer>(); } public void arrayCompare(int[] arr1, int[] arr2) { Arr1.equals(arr2); } public int valueOf(int x) { try { return a[x]; } catch (ArrayIndexOutOfBoundsException e) { return -1; } }
Page 15
Coding_Rule
try { int i = 0; while (true) { method(a[i++]); } } catch (ArrayIndexOutOfBoundsException e) { } try { new Executer().execute(); } catch (Exception e) { System.out.println("An unexpected error has occurred."); e.printStackTrace(); System.exit(ERR_CODE); } /** */ void method() { ... }
for (pos = 0; pos < a.length && a[pos] != c; pos++) ; int getValue() { int ret = 1; try { ... return ret; } catch (IOException e) { ... } finally { Ret = 0; // The return value cannot be set to 0. } ...
Page 16
Coding_Rule
class MyClass { ... void method() { if (value == null) { throw new InnerError(); } ... } } // Internal error class InnerError extends Error { ... public void open(File file) { if (!file.exists()) { throw new Exception("File not found."); } .... }
public void method(String str) { if (str == null) { throw new RuntimeException("IllegalArgument"); } .... }
public class ValueObject { ... } ... ValueObject value; ... ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.obj")); Oos.writeObject(value);
Page 17
Coding_Rule
public class Super { protected void foo() { // ... } } public class Sub extends Super {
public void foo() { // ... } }
public class Super { protected void foo() { // ... } } public class Sub extends Super {
public void foo() { // ... }
Page 18
Coding_Rule
Corrected example
import java.util.List;
public class MyClass { private static final String CLASS_NAME = "MyClass"; public boolean isMatch(String name) { return name.equals(CLASS_NAME); } public String getName() { return CLASS_NAME; } } try { num = Integer.parseInt(data.nums[index]); } catch (NumberFormatException e) { System.out.println("A non-numeric value has been specified."); } String str; ... if (str == null || str.length() == 0) { ... if (str != null && str.length() > 0) { public class MyClass { public MyClass() { if (flag) { method(1); } else { method(1.5f); } } // This is executed when "flag" is true. private void method(int n) { ... } // This is executed when "flag" is false. private void method(float f) { ... } try { data = text.getBytes("UTF-8"); ... } catch (UnsupportedEncodingException e) { // Exceptions that are not checked are thrown as internal errors. throw new InternalError(e); }
Page 19
Coding_Rule
public class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } try { ... } catch (IOException e) { ... } finally { in.close(); } if (arg != null) { ... } else { throw new IllegalArgumentException("arg"); } String str; ... if(str == null) { ... } class MyClass { Private String str = null; MyClass() { } } public String getFileName(String key) { File file = fileManager.getFile(key); if (file == null) { return null; } return file.getName(); } File dir = new File("dir"); if (!dir.mkdir()) { if (!dir.isDirectory()) { throw new IOException("Directory creation failed. : " + dir.getAbsolutePath()); } } class Foo{ public String[] getArray() { ... return new String[0]; } }
Page 20
Coding_Rule
boolean check(String str) { if (str.equals("abc")) { .... } else if (!str.equals("xyz")) { .... } else { .... } } switch (i) { case 1:
case 2: ... break; default: }
class Foo{ private static final Logger logger = Logger.getLogger( Foo.class ); public void doSomething () { logger.log("BEGIN of doSomething"); ... } } class Foo{ private static final Logger logger = Logger.getLogger( Foo.class ); public void doSomething () { try { ... } catch (IOException ioe) { logger.log("ERROR0502", ioe); } }
Page 21
Coding_Rule
int index = string.indexOf("pattern"); String subString = null;
if (index >= 0) { subString = string.substring(index); ... } else { ... }
for (int i = 0; i < list.size(); i++) { Foo foo = null; foo = (Foo)list.get(i); ... } public void test(char ch){ if(Character.isWhiteSpace(ch)){ ...
Page 22
Coding_Rule
public class MyClass { private void bMethod() { ... } void cMethod() { bMethod(); } } public class MyClass {
protected List list; ... private class ListImpl implements List { ... } }
Page 23
Coding_Rule
public class MyClass {
public List list; ... private class ListImpl implements List { ... } } class SuperClass {
... } else if (arg.equals("-q")) { ... } else if (arg.equals("-r")) { ... } else { throw new IllegalArgumentException("arg"); }
public class MyClass { private String name; public void setName(String name) { if (this.name == null) {
this.name = name; } } }
The number of "if", "for", "while", "do-while", "catch" blocks, "case" labels, logical operators and conditional operators inside a class The number of "if", "for", "while", "do-while", "catch" blocks, "case" labels, logical operator and conditional operators inside a method public class MyClass { Private final Map<String, Integer> map = new HashMap<String, Integer>(); } public void arrayCompare(int[] arr1, int[] arr2) { Arrays.equals(arr1, arr2); } int valueOf(int x) { if (x < 0 || x >= a.length) { return -1; } return a[x]; }
Page 24
Coding_Rule
for (int i = 0; i < a.length; i++) { method(a[i]); } try { new Executer().execute(); } catch (Exception e) { ///^ #IllegalCatch Catch at an entry point System.out.println("An unexpected error has occurred."); e.printStackTrace(); System.exit(ERR_CODE); } /** * Explanation of the method</em> */ void method() { ... } for (pos = 0; pos < a.length && a[pos] != c; pos++) { continue; }
Page 25
Coding_Rule
class MyClass { ... void method() { if (value == null) { throw new InnerException(); } ... } } // Internal error class InnerException extends RuntimeException { ... public void open (File file) { if (!file.exists()) { throw new FileNotFoundException(file.toString()); } .... }
public void method(String str) { if (str == null) { throw new IllegalArgumentException("str"); } .... } class MyClass { private String str; MyClass() { str = null; } } public class ValueObject implements Serializable { private static final long serialVersionUID = ... } ... ValueObject value; ... ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.obj")); Oos.writeObject(value);
Page 26
Coding_Rule
public class Super { protected void foo() { // ... } } public class Sub extends Super {
protected void foo() { // ... }
public class Super { protected void foo() { // ... } } public class Sub extends Super {
protected void foo() { // ... }
public class MyClass { ... // When the class is not used from the outside
private class MyNestedClass { ... } }
Page 27
Coding_Rule
Description This rule checks whether type-import-on-demand statement or static-import-ondemand statement is used or not. If type-import-on-demand statement is used, readability of the source will decline because it will be difficult to determine which package's class is called on the source. And, when a class is added in an on-demand imported package and its name is redundant with the other on-demand imported class, a compilation error will occur. It is recommended to describe single-type-import statements piece by piece.
Page 28
Coding_Rule
If implementation has been inadvertently omitted from this "finally" block, add the implementation. If implementation is intentionally omitted, delete the block to avoid confusion.
This rule checks whether fields are explicitly initialized by a variable initializer, initialization block, or constructor. If initialization of a field is omitted, the field is initialized with the default value for the field type. If the initial value is meaningful, the field should be initialized explicitly. This rule checks whether NullPointerException is caught. NullPointerException occurs when an instance method is invoked for a NULL object or when the field of a NULL object is accessed. You should conduct a NULL check before referencing any object so that a NullPointerException is not generated. Since the costs in generating, throwing, and catching an exception are high, a NullPointerException might considerably degrade performance, compared with checking in advance.
Page 29
Coding_Rule
This rule checks whether strings are compared using "==" or "!=". When String objects are compared by using an equality operator ("==" or "!="), a comparison is made between objects, not strings. To compare strings, use the equals() method for String objects.
This rule checks whether a "default" label is written at the end of each "switch" block. To prevent the code from operating abnormally if the condition evaluates an unexpected value, a "default" label should be written at the end of each "switch" block. Even if there is to be no processing, you should write a "default" label with a comment, which explicitly indicates that the required error handling is not inadvertently omitted. Although "default" labels can be written before "case" labels, for better
Page 30
Coding_Rule
A return value of String.indexOf() or String.lastIndexOf() must be checked if it is a non-negative value. Make sure that a return value of String#indexOf() or String#lastIndexOf() is checked.
A created instance might not be used. This rule checks whether deprecated classes, methods, constructors, fields or annotations are used.</p> It is recommended to use alternate classes, methods, constructor, fields or annotations. When primitive wrapper objects are compared with an equality operator ("==" or "!="), a comparison is made between objects, not the values. To compare values of primitive wrapper objects, use the equals() method. This rule checks for local variables that have the same name as a field. If a local variable and a field have the same name, the local variable hides the field. As a result, the readability of the source is decidedly degraded. Local variables should have names that are different from, and are not similar to, any field names. This rule checks whether the interface specified in the "extends" or "implements" clause is included in the supertype of classes or interfaces specified in the phrase. Duplicate implementation of an interface included in a supertype is possible but redundant. This rule checks whether a visibility higher than ${visibility} is specified for a nonfinal field. Excessively heightening the visibility of a non-final field will degrade capsulation ability. If you want to use the field as a constant, explicitly declare it as final. If you do not want to use the field as a constant, lower the field visibility, and use a Setter or Getter to access the field from other classes. This rule checks whether there is a non-static field with the same name as a superclass field (private fields are not checked). A non-static field with the same name as a superclass field hides the superclass field, and makes it difficult to recognize which field is being accessed. Non-static fields should have names that are different from, and are not similar to, any superclass field names. This rule checks whether there is a method that has the same signature as a superclass "private" method. Since a superclass "private" method is invisible from a subclass, declaration of a method with the same signature in a subclass is not assumed as an override. However, the implementer might think such a method is an override or such a method might make it difficult to understand the code. Therefore, you should avoid using the same signature as a superclass "private" method, for example, by renaming the method.
Page 31
Coding_Rule
This rule checks whether a static method is hidden. Redefining a non-static method in a subclass is an override of the method, but redefining a static method in a subclass results in the hiding of the method. For an override, whether a subclass method or superclass method is invoked depends on the runtime instance class (dynamic binding). When hiding is used, the method that is invoked depends on the declared class (static binding).
This rule checks for "private" fields that are used in only one method. Consider replacing such fields with a local variable.
This rule checks whether there are "private" methods and constructors that are not used from within the class (readObject, readResolve, readObjectNoData, writeReplace, and writeObject are not checked). Note that the check ignores default constructors because they might be written to prohibit instantiation from other classes. If processing that requires this method is inadvertently omitted, implement the processing. In other cases, delete this unused method to avoid confusion. This rule checks whether a class type with a visibility lower than "protected" is specified for a "protected" field. From the viewpoint of class design, it is not recommended that you use a type with a visibility lower than that of the declared field type for the field. This rule checks whether a class type with a visibility lower than "protected" is specified for a parameter or return value of a "protected" method. From the viewpoint of class design, it is not recommended that you use a type with a visibility lower than that of the declared method type for a parameter or return value of the method. If such a type is specified for the parameter or return value, the type might be invisible from the caller of the method.
Page 32
Coding_Rule
This rule checks whether a non-public class is specified for the type of a public field. From the viewpoint of class design, it is not recommended that you use a type with a visibility lower than that of the declared field type for the field.
This rule checks whether "super." is written to reference a superclass field. When accessing a superclass field, you should write "super." to explicitly indicate a superclass field.
This rule checks whether the "else" statement for an "else-if" statement is written. If the corresponding "else" statement is missing, check whether consideration of an abnormal case has not been inadvertently omitted.
When a parameter with the same name as an accessible field is defined, this rule checks whether the parameter is referenced anywhere other than an assignment statement ("=" only) for the field. If a parameter is defined with the same name as a field, the parameter hides the field. It is possible to distinguish between them by adding "this" to the field name, but omission of "this" can lead to a bug. Note, however, that parameter readability must not be degraded by avoiding confusion with a field name. The following coding rules might be useful as preventive measures: Add a prefix such as "a" to all method parameters. Add a prefix or suffix such as "_" to all field names.
Page 33
Coding_Rule
This rule checks whether the constructor BigDecimal(double) is invoked. When an instance of java.math.BigDecimal is created with the constructor BigDecimal(double), a precision of values expressed by the instance is degraded. It is recommended to invoke constructors which preserve precisions.
Page 34
Coding_Rule
This rule checks whether a new instance of the java.lang.Error class or its subclasses is created. There are two types of exceptions that are not checked: runtime exceptions (subclasses of java.lang.RuntimeException) and errors (subclasses of java.lang.Error). Normally, these are used to report conditions that cannot be recovered on the caller side. To implement an exception that is not to be checked, use a runtime exception. An "error" is an exception used when Java VM cannot continue processing for some reason such as resource insufficiency, and should not be used in applications. This rule checks whether a new instance of java.lang.Exception is created. The java.lang.Exception class is a superclass of an exception to be checked. Since the Exception class cannot indicate the status when an exception has occurred, the subsequent exception handling becomes obscure. To clarify what kind of exception has occurred and what kind of exceptions should be caught, you should use an Exception subclass that is suitable for indicating the status when an exception has occurred. This rule checks whether the construcotr Random(long) is invoked. Because pseudorandom numbers generated by Random(long) constructor can be predicted, the security will be degraded when using the pseudorandom numbers. It is recommended to use more secure pseudorandom number generated by java.security.SecureRandom class and so on. This rule checks whether a new instance of java.lang.RuntimeException is created. The "java.lang.RuntimeException" class is a superclass of a runtime exception class. The RuntimeException class cannot indicate what runtime exception has occurred. You should use a RuntimeException subclass that is suitable for indicating the status when an exception has occurred.
A non-serializable object seems to be written to ObjectOutput. If a non-serializable object is passed to ObjectOutput#writeObject(), this causes an error.
Page 35
Coding_Rule
This rule checks whether there is a static field with the same name as a superclass field (private or final fields are not checked).</p> A static field with the same name as a superclass field hides the superclass field, and makes it impossible to recognize which field is being accessed. Static fields should have names that are different from, and are not similar to, any superclass field names. This rule checks whether a non-final public field is used. Since a non-final public field is able to be accessed from all classes, it will degrade capsulation ability. If you want to use the field as a constant, explicitly declare it as final. If you do not want to use the field as a constant, lower the field visibility, and use a Setter or Getter to access the field from other classes. This rule checks whether the access modifier of an inner class (a non-static nested class) is "private". To create an inner class instance, an outer class instance is required. To externally expose a nested class, you should use a "static" class.
Page 36
Comments
S.No. Category 1 2 3 4 5 6 Description Summary of method specifications Argument's explanation(@param) Return value's explanation(@return) The name of the possible exception is thrown(@exception) Refer to class or method(@see) Already Introduced version information(@since)
1 2 3 4
Method document comment Class document comment Logical comment Variable level comment
Page 37
Definition
S.No. Category
Class
2 3
Method Variable
Page 38
Definition
Description 1 class/interface documentation comment 2 class/interface design 3 class/interface implementation comment 4 classstaticvariable Declare variables in the order of public class variableprotected class variablePackage level variableprivatevariable 5 Instance variable Declare variables in order of public variableprotected variable,package level variableprivate variable 6 Initializer. 7 Constructor 8 Method documentation comment Method level comment Declare variables Program logic Return value Assign initial value
Page 39