02.coding Conventions
02.coding Conventions
Coding Conventions
On behalf of
On behalf of
Approved by:
Approved by:
Project Advisor
Date
Project Advisor
Date
Project Manager
Date
Ms. Chinda Aksornukul
Date
Project Manager
Date
Date
Project Leader
Project Leader
Prepared By
Date
Mr. Yusuf
Mr. Danilo Nuestro
Revision History
Date
15 March 2006
30 May 2006
28 Jun 2006
Updated by
Yusuf
Dani
Dani
Revision
0.1
0.2
0.3
Update Point
newly created
Modified based on FSBT meeting
Modify the names from TMAP to using TMAP
Phase
Block Name
Document Name
Project Name
Table of Contents
Table of Contents
Created
Updated
2006-03-09
2006-06-14
Page
By
By
3/163
Yusuf
Dani
Phase
Block Name
Document Name
Project Name
Appendix A
App A - SqlTips
Table of Contents
Created
Updated
2006-03-09
2006-06-14
Page
By
By
4/163
Yusuf
Dani
Phase
Block Name
Document Name
Project Name
Appendix B
App B - SQL Standards
Table of Contents
Created
Updated
2006-03-09
2006-06-14
Page
By
By
5/163
Yusuf
Dani
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
1. Introduction
Created
2006-03-09
By
Yusuf
Updated
2006-06-14
By
Dani
1. Introduction
1.1
Purpose
It is necessary as a System Development Vendor to provide a source code program that is easy to understand and to maintain.
Even though TMAP alone will not have a chance to change the code, but for the continuity of maintaining the application, a readable and understandable source code
is considerably very important. Therefore, this document provide a Coding Convention as a Guideline for any System Development Vendor to develop
a new system application.
1.2
Scope
This document cover a Guideline for Coding Convention for Java according to standard Java Coding Convention provided by Sun Microsystem,
Coding Convention for Batch processing, Coding Convention for SQL, and Coding Convention for Shell scripting.
For rules which are not described here, can be refer to Naming Convention as a General Rules.
1.3
Additional
For TMAP standard, we can use the CheckStyle Developer tool to validate and check if the codes written adheres to the coding standard as set by Sun
Microsystems.
http://checkstyle.sourceforge.net/
SQL design standards and correct approach are included in this document as an appendix.
6/163
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
2006-03-09
By
Teguh
Updated
2006-06-14
By
Dani
* Client Name
: TOYOTA
* Program Id
: CommonUtil.java
* Author
: Ajay K P
* Version
: XX.XX.XX
* Creation Date
: 2005/12/20
*
* Update history
* XX.XX.XX
Notes :
- version is not a version set up with tools, such as VAJ.
* Program History :
Re-fix date
20001013
Person in charge
XXXXX
Description
XXXXXXXXXXXXXXXXXX
*
* Copyright(C) 2006-TOYOTA Motor Corporation. All Rights Reserved.
*************************************************************************************************/
7/163
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
8/163
Created
2006-03-09
By
Teguh
Updated
2006-06-14
By
Dani
Phase
Project Name
Block Name
Document Name
Function Name
Coding Conventions
9/163
Page
Title
Created
2006-03-09
By
Teguh
Updated
2006-06-14
By
Dani
Notes :
*<pre>
@see sms.Test
*</pre>
*
* @author An implementor name is described (describe with a half-width alphabetic character).
* @version XX.XX.XX
* @see Linking to the HTML file to refer to
*/
Notes :
* @return
* @exception
* @throws
Throws SecurityException
*/
Phase
Project Name
Block Name
Document Name
Coding Conventions
10/163
Page
Function Name
Title
Created
2006-03-09
By
Teguh
Updated
2006-06-14
By
Dani
d. Property comment
A title is attached by a header comment for every property.
A JavaDoc functionality is taken into consideration.
/**
Notes :
*/
e. Other comment
Use '/* - */' or '//' for comment
//Comment about Variable XX
Notes:
String XX = null;
- for // single line comments, it would only describe the next line code.
- for /* */ multi-line comments, it would describe the next group of codes.
/*
*/
String fileFullName = getInFileDir()+getInFileName();
File f = new File(fileFullName);
try{
fw = new FileWriter(fileFullName,true);
}catch(IOException e){
ErrorLog.write("XXX.setFile>>create file writer error");
rc = false;
}
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
2006-03-09
By
Teguh
Updated
2006-06-14
By
Dani
Refix date
Person in charge
Description
01.00.00
20000418
Toyota)Taro
New creation
01.01.00
20000520
Toyota)Taro
01.01.01
20000704
Toyota)Taro
Bug-fix
:
b. The comment in a code
Update history is described in the revise part of a source code.
A descriptive content is made up of a 'version' and the 'description of a updation'.
:
/* START: 01.01.00
20000520
Toyota)Taro
if ( !indir.endsWith(System.getProperty("file.separator")) ) {
setInFileDir( indir + System.getProperty("file.separator") );
}
/* END: 01.01.00
20000520
Toyota)Taro
11/163
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Recommended Sample
N_GNR002 Do not distinguish name / variable only by small letter or capital letter
In the java specification, capital letter and small letter is treated differently, but do not create name
Explanation /
Motive
Recommended Sample
Updated
3/9/2006
By
By
12/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
A.2.2. Package
N_PKG001 Use small letter for package name
Explanation /
Motive
Unless there is a specific agreement, use small letter for package name.
This is the common rule of java
Not Recommended Sample
th.co.toyota.isid.FrameWork.Banking.ACCOUNT
Recommended Sample
th.co.toyota.framework.banking.account
th.co.toyota.framework.banking.a00001
Recommended Sample
th.co.toyota.framework.banking.account
th.co.toyota.fw.bkg.acc
Recommended Sample
th.co.toyota.framework.banking.account
It is possible to have the same sub package name if parent package is different
(FQDN is unique)
Not Recommended Sample
th.co.toyota.framework.banking.account
th.co.toyota.framework.trading.account
Recommended Sample
13/163
Created
3/9/2006
By
Teguh
Updated
2006-06-14
By
Dani
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
14/163
Created
3/9/2006
By
Teguh
Updated
2006-06-14
By
Dani
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
A.2.3. Class
N_CLS007 Use class name which represent the role of that class
Dont use name which is not meaningful for class name, such as function ID or sequential
Explanation /
Motive
number. By using meaningful one, class contents can be associated from class name, and
the code will be more readable.
Not Recommended Sample
Recommended Sample
Use capital letter for the first letter of class name. If class name is made up from multiple word,
use capital letter for the first letter of each word. This is the common rule of Java
Not Recommended Sample
Recommended Sample
Put "Exception" at the end of exception class name. By this standardization, the code will be more
readable
Not Recommended Sample
Recommended Sample
Updated
3/9/2006
By
By
15/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
}
N_CLS006 Abstract class naming follows class naming
Naming rule for abstract class name basically follows the naming rule of class name.
Explanation /
Motive
When we define this type of interface, use adjective (~able) which represent that ability as
class name. By this standardization, the code will be more readable by others.
Sample
Updated
3/9/2006
By
By
16/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
17/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
Use [AllTest] or [package name + Test] for class name of class which performs all test and
package test. By this standardization, the code will be more readable by others.
Sample
Updated
3/9/2006
By
By
18/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
19/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.2.5. Method
N_MTD001 Don't make a method which has the same name with constructor
Explanation /
Motive
Recommended Sample
public BadSample() {
public FixedSample() {
If method name consists only one word, use small letter. If method name is made up from multiple
words, for the second word and after use capital letter for the first letter of the each word.
Not Recommended Sample
Recommended Sample
N_MDT003 Use ["create" + object name] for method name which create object
The name for method which create object (factory method) should start with "create" and
Explanation /
Motive
The name for method which convert object to another object (converter method) should start
Updated
3/9/2006
By
By
20/163
Teguh
Phase
Project Name
Block Name
Document Name
Explanation /
Motive
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
by attribute name. By this standardization, the code will be more readable by others.
This is the convention of JavaBeans
Sample
by attribute name. By this standardization, the code will be more readable by others.
This is the convention of JavaBeans
Sample
Updated
3/9/2006
By
By
21/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
role paired. By this standardization, the code will be more readable by others.
For example send and receive, top and bottom, width and height
Sample
Updated
3/9/2006
By
By
22/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
23/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
A.2.6. Argument
N_PRM001 Don't use the same name for method parameter and instance variable
Explanation /
Motive
Don't use name for method argument which conflict with class member. If same name is used,
put "_" at the start or use "this". By this standardization, the code will be more readable by others.
Not Recommended Sample
Recommended Sample
Updated
3/9/2006
By
By
24/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
25/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Even if above rule is followed, It does not make any sense if the situation does not properly
represented
Example : Variable which is used as a flag whether stock is exist or not
O hasStock
X isStock
Sample
constant name is made up from multiple words, use "_" as a separator for each word.
By this standardization, the code will be more readable by others.
Not Recommended Sample
Recommended Sample
public static final int SAMPLE_VALUE = 10;
Updated
3/9/2006
By
By
26/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Recommended Sample
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
27/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Recommended Sample
import java.io.*;
import java.io.*;
try {
try {
System.out.println (str1);
System.out.println (str2);
br.close();
br.close();
} catch (IOException e) {
} catch (IOException e) {
e.printStackTrace ();
e.printStackTrace ();
}
}
}
}
Updated
3/9/2006
By
By
28/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
N_LVL002 Use "i", "j", "k", for loop counter at each nest in FOR statement
Explanation /
Motive
As loop counter in FOR statement, use "i", "j", "k" (alphabetically sorted) for each hierarchy.
By this standardization, the code will be more readable by others
Not Recommended Sample
Recommended Sample
for (int i = 0; i < 10; i++ ) {
}
}
}
}
Updated
3/9/2006
By
By
29/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
30/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
interface is the improvement of code flexibility. When declaring using implementation class, if the
implementation class is changed afterwards it is necessary to change all the reference locations.
On the other hand, the implementation class can be changed only by changing the instance generation
part if we declare by using interface
Not Recommended Sample
Recommended Sample
import java.util.*;
import java.util.*;
badSample.badMethod(sampleList);
fixedSample.fixedMethod(sampleList);
}
}
Updated
3/9/2006
By
By
31/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Do not use deprecated method or class. If those functions are needed, please refer to the
alternate solution written in JavaDoc
Not Recommended Sample
Recommended Sample
import java.util.Date;
import java.util.Calendar;
System.out.println (sampleDate.getYear());
System.out.println (sampleCalendar.get(
Calendar.YEAR));
will decrease, and waste some resources. Delete the one that no longer needed.
Not Recommended Sample
Recommended Sample
public class BadSample {
usedMethod ();
}
usedMethod ();
Updated
3/9/2006
By
By
32/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Understand the meaning of access modifier such as private and public, and then declare class,
method, and variable with proper modifier
Not Recommended Sample
Recommended Sample
not inherited, method that is not overridden, or variable that its value does not change (constant).
It will increase code readability.
Not Recommended Sample
Recommended Sample
public class FixedSample {
C_GNR005 Understand the difference between primitive type and reference type (definition)
The characteristic of primitive type and reference type, mainly differs in the following 3 points
- Execution speed and resource consumption
- Default value (When declaring instance variable)
- Data structure
The following is the explanation of each difference
- Execution speed and resource consumption
Different from reference type, primitive type does not create new object when we use it.
As a result, time and resource can be saved.
- Default value (when declaring instance variable)
Primitive type : depends on the type
Reference type : null
Updated
3/9/2006
By
By
33/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
(byte) 0
short
(short) 0
int
long
0L
float
0.0f
double
0.0d
char
\u0000'
boolean
false
- Data Structure
Explanation /
Motive
Updated
3/9/2006
By
By
34/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Stack
Page
Function Name
Title
5 // i's value
Primitive type
Created
5 // j's value
k
Reference type
C_GNR005 Understand the difference between primitive type and reference type (argument)
Is the difference of behavior between primitive type and reference type when those is passed
as a parameter of a method understood? The value is passed when the argument is primitive
Explanation /
Motive
type, and the reference to the instance is passed as a value for the reference type.
Therefore, if the state of reference type argument is changed in a method, it will cause
inconsistency when the instance is referred from multiple locations.
Do not manipulate passed argument directly in a method which has reference type or argument
Sample
import java.awt.Point;
public class Sample {
public static void main (String[] args) {
int intValue = 0;
Point point = new Point (0, 0);
Sample sample = new Sample ();
sample.printValue(intValue, point);
sample.modifyValue(intValue, point);
sample.printValue(intValue, point);
}
private void modifyValue(int value, Point point) {
value = 10;
Updated
3/9/2006
By
By
35/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
point.setLocation(55, 77);
}
private void printValue(int value, Point point){
StringBuffer buffer = new StringBuffer();
buffer.append(value);
buffer.append(" : ");
buffer.append(point);
System.out.println(buffer);
}
}
Execution Result
0 : java.awt.Point[x=0,y=0]
0 : java.awt.Point[x=55,y=77]
Example above handles primitive type variable intValue and reference type variable point
As seen from the result, before and after the execution of modifyValue() method primitive type intValue has
not been changed, but reference type point has been changed
For primitive type intValue, copy of the value is passed as an argument. The manipulation is performed to the
copy, therefore does not affect intValue itself. On the other hand, for reference type point, reference of the
value is passed as an argument. Therefore manipulation within the method will affect the value to which
point refers
Updated
3/9/2006
By
By
36/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.2. Metrics
C_MTR001 Number of line in a method should be less than 20
Explanation /
Motive
The ideal number of line in a method , including comment, is 20 lines, at most 150 lines.
If the number of line exceeds this value, review the design, divide method into multiple methods
The ideal number of line in a class, including comment, is 600 lines, at most 1000 lines.
If the number of line exceeds this value, review the design, divide class into multiple classes
code gets complex, readability/maintainability will decrease, and the possibility of bug occurrence
gets bigger.
Updated
3/9/2006
By
By
37/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.3. Format
C_FMT001 Use blank space instead of tab
Do you use tab for code indent? If we use tab and blank space for indent, depends on editor
Explanation /
Motive
setting, the indent can be wrong. It will cause the readability of the code decrease.
Use blank space instead of tab for indent. If you feel troublesome to put blank space each time,
do batch conversion at the end by using the replace function of editor
Not Recommended Sample
Recommended Sample
public class FixedSample {
return area
return area
Recommended Sample
public class FixedSample {
return area
return area
}
Updated
3/9/2006
By
By
38/163
Teguh
Phase
Project Name
Block Name
Document Name
Function Name
Coding Conventions
Page
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
39/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Do not put any statement after "{". It will cause code readability decrease. Put in new line
even if it is a short statement.
Not Recommended Sample
Recommended Sample
private void fixedSampleMethod () {
int i = 0;
}
Do not write more than one statement in a line. Code readability will decrease. Put in a new line
even for short statement
Not Recommended Sample
Recommended Sample
public int fixedSampleMethod (int top, int bottom) {
Recommended Sample
C_FMT007 Put blank space before and after assignment operator (=, +=, -=, ...)
Explanation /
Motive
Put blank space before and after assignment operator (=, +=, -=, ...). It will improve code
readability
Not Recommended Sample
Recommended Sample
a=1;
a = 1;
b-=a;
b -= a;
Updated
3/9/2006
By
By
40/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Put blank space after semicolon in FOR statement. It will improve code readability
Not Recommended Sample
Recommended Sample
C_FMT009 Do not put blank space between "--" or "++" and operand
Explanation /
Motive
Do not put blank space between prefix/postfix unary operator "--" or "++" and operand
It will become confusing as mistaking those for other operator
Not Recommended Sample
Recommended Sample
System.out.println(value : + ++ a);
System.out.println(value : + ++a);
System.out.println(value : + a ++);
System.out.println(value : + a++);
C_FMT010 Put blank space before and after bit operator ("|", "&", "^", "<<", ">>")
Explanation /
Motive
Put blank space before and after bit operator. It will improve code readability
Not Recommended Sample
Recommended Sample
int a = x >>y;
int a = x >> y;
int b = a& x;
int b = a & x;
int c = x^y;
int c = x ^ y;
Updated
3/9/2006
By
By
41/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
C_FMT011 Put blank space before and after binary operator ("||", "&&")
Explanation /
Motive
Put blank space before and after binary operator. It will improve code readability
Not Recommended Sample
Recommended Sample
if (a|| b){
if (a || b){
if (a &&b){
if (a && b){
if (a&&b){
if (a && b){
C_FMT012 Put blank space before and after relational operator ("<", ">", ">=", "<=", "==", "!=")
Explanation /
Motive
Put blank space before and after relational operator. It will improve code readability
Not Recommended Sample
Recommended Sample
if (a<= b){
if (a <= b){
if (a ==b){
if (a == b){
if (a!=b){
if (a != b){
Updated
3/9/2006
By
By
42/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
C_FMT016 Put blank space before and after arithmetic operator ("+", "-", "*", "/", "%")
Put blank space before and after arithmetic operator. It will improve code readability
Explanation /
Motive
Recommended Sample
if (a+ b){
if (a + b){
if (a %b){
if (a %b ){
if (a/b){
if (a / b){
Explanation /
Motive
statement, and code readability will decrease. If there is any operation that needs parenthesis,
finish the operation beforehand.
Not Recommended Sample
Recommended Sample
return (a + b);
return a + b;
return (int) a;
because variable itself shows the result of condition. Therefore, comparing with true is
redundant, and can decrease code readability.
Not Recommended Sample
Recommended Sample
while(hasStock == true) {
while(hasStock) {
if(hasStock == true){
if(hasStock){
Updated
3/9/2006
By
By
43/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Explanation /
Motive
When comparing with constant, put the constant in the right side
Put in the left side for variable which is the center of operation and appears several times in
the code
Not Recommended Sample
Recommended Sample
if( a < i ){
if( a < i ){
Updated
3/9/2006
By
By
44/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
A.3.4. Comment
C_CMT001 Write at least author and version (class), param, return and exception (method) in Javadoc comment.
Write Javadoc comment for class, method, field as shown below, especially for those which
declared as public or default. Also write another tag if necessary.
[Javadoc comment format]
Start with /**
Second line and below, start with *, then write the statement in Javadoc tag
End with */
[Class]
@author [author]
Describe class creator and those who update. Describe each at a tag if exist more than one
@version [version]
Describe class version
Explanation /
Motive
[Method]
@param [name] [explanation]
Describe parameter name and its explanation by declaration order
@return [explanation]
If exists, explain the return value
@exception [name] [explanation]
Write the exception which can be thrown when the method is called and its explanation
[Field]
Explanation about field
Describe variable name as much as possible. When it is not possible to show, write
explanation as Javadoc comment
Sample
Updated
3/9/2006
By
By
45/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
/**
* Sample class for explaining how to write Javadoc
* @version 1.0
* @author Tsuyoshi Wakahara
*/
public class JavadocSample {
/**
* Explanation of sampleMethod
* @param value argument's explanation
* @return return value's explanation
* @exception SampleException exception's explanation
*/
public String samleMethod(String value) throws SampleException{
String returnValue = SAMPLE;
return returnValue;
}
}
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
46/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Recommended Sample
public class FixedCommentSample {
/**
/**
*/
*/
int sum = 0;
int sum = 0;
sum += elements[i];
return sum;
}
Updated
3/9/2006
By
By
47/163
Teguh
Phase
Project Name
Block Name
Document Name
}
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
48/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
A.3.5. Import
C_IMP002 Do not import java.lang package
Explanation /
Motive
Do you know that java.lang package is imported implicitly? Developer should not import java.lang
package explicitly
Not Recommended Sample
Recommended Sample
import java.lang.*;
public class BadSample {
Updated
3/9/2006
By
By
49/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.6. Class
C_CLS001 Declare as final for class which will not be inherited
Declare final for class which is not inherited. Below are its advantages
1. That the class inheritance and method overriding don't exist will be notified to the compiler,
Explanation /
Motive
Recommended Sample
C_CLS002 The order of declaring the field is the order of public, protected, default, and private.
Explanation /
Motive
When fields are declared, is the order taken into consideration? To keep the readability of the
code, declare the field according the access modifier
Not Recommended Sample
Recommended Sample
public class FixeddSample {
int rank;
int rank;
Updated
3/9/2006
By
By
50/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.7. Constructor
C_CRT001 Do not declare public constructor in a class which is not declared as public
Do not create public constructor for non-public class. The constructor
Explanation /
Motive
of non-public class cannot be accessed. For example, we can not compile class from another
package which call constructor shown in "Not Recommended" sample below. To avoid this,
remove public modifier from constructor, or add public modifier to class
Not Recommended Sample
class BadSample {
Recommended Sample
class FixedSample {
public BadSample () {
FixedSample () {
Recommended Sample
public class FixedSample {
public FixedSample(){
number = num;
this(10);
Updated
3/9/2006
By
By
51/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.8. Method
C_MTD001 Declare as final for method which will not be overridden
Can the method be overridden by subclass? If we already knew that the method will not be
overridden, then declare it as final. That the method will not be overridden will be notified to the
Explanation /
Motive
compiler, so that complier can generate optimized code. As a result, the performance will improve
Not Recommended Sample
Recommended Sample
the client that uses the method should write the logic of an extra null checking.
Create method to return 0 size of array, and not null value.
Not Recommended Sample
Recommended Sample
import java.util.List;
import java.util.List;
if (slist.size() == 0){
return null;
new String[slist.size()]);
} else{
return result;
}
}
Updated
3/9/2006
By
By
52/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
C_MTD003 Design public method such that it will not break consistency of class.
Explanation /
Design public method carefully such that it will not break class consistency
Motive
Not Recommended Sample
Recommended Sample
Class below keep stockRightSpeaker and stockLeft
stockRightSpeaker =
stockRightSpeaker =
stockRightSpeaker-quantityRight;
stockRightSpeaker-quantity;
stockLeftSpeaker =
stockLeftSpeaker-quantity;
stockLeftSpeaker =
stockLeftSpeaker-quantityLeft;
}
}
Here, the value of stockRightSpeaker and stockLeft
Speaker can be changed from outside class using
respective buy method. However, if only one of those
value is changed, the assumption of speaker is sold
in a pair of left / right speaker will break.
}
}
Updated
3/9/2006
By
By
53/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Recommended Sample
import java.awt.Point;
public class BadSample {
smpl.switchXandY(point);
smpl.printValue(point);
smpl.switchXandY(point);
smpl.printValue(point);
sb.append("X is ");
sb.append(point.getX());
double x = point.getX();
sb.append("and Y is ");
double y = point.getY();
sb.append(point.getY());
point.setLocation(y, x);
System.out.println(sb);
}
// Display
double x = point.getX();
double y = point.getY();
sb.append("X is ");
point.setLocation(y, x);
sb.append(point.getX());
sb.append("and Y is ");
sb.setLength(0);
sb.append(point.getY());
sb.append("X is ");
System.out.println(sb);
sb.append(point.getX());
sb.append("and Y is ");
}
}
Updated
3/9/2006
By
By
54/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
sb.append(point.getY());
System.out.println(sb);
}
}
reason? There is no advantage of using "this" as a return value. Use void or another value as
a return value of method
When a method is invoked, the invoker has a reference to that object. There is no point of returning "this".
For convenience there are some cases of returning "this" like the following sample. Method invoking at point 1 can
be written like point 2.
1
2.
sample.sampleMethod1().sampleMethod2().sampleMethod3();
method is executed without checking the type of argument in source code. Source code
readability will decrease as explanation written below
Explanation
In the following sample, three kind of classify() methods are created to distinguish object. In main() method, we
create an instance and call classify() methods.
public class BadSample{
Updated
3/9/2006
By
By
55/163
Teguh
Phase
Project Name
Block Name
Document Name
Function Name
Coding Conventions
Page
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
56/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Do not we use object name when invoking class method. Use class name when calling class method
By following this rule, code readability will improve.
Not Recommended Sample
Recommended Sample
public class FixedSample {
object.sampleClassMethod();
FixedSample.sampleClassMethod();
}
}
}
}
Updated
3/9/2006
By
By
57/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
Do not declare multiple variables in a statement. It will decrease code readability and maintainability. Declare only one variable in a statement.
Not Recommended Sample
Recommended Sample
public class FixedSample {
(Both the numerical value and the character string are included). The use of literal will cause the
code readability and maintainability decrease. Please use the literal constant (final static field) to
prevent this.
Exception : -, 1, 0 and 1, etc. When it is used as counter in a loop
Not Recommended Sample
Recommended Sample
public class FixedSample {
Updated
3/9/2006
By
By
58/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
The declaration form like the following "Not Recommended Sample" seems to remain as
an influences of C language.
Not Recommended Sample
Recommended Sample
public class FixedSample {
It takes more time to access the class variable and the instance variable compared with the
access to the local variable. Please use the local variable if you frequently access the it as far as
possible.
Not Recommended Sample
Recommended Sample
public class FixedSample {
result += numbers[i];
tempSum += numbers[i];
}
result = tempSum;
}
Updated
3/9/2006
By
By
59/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
It can be specified that this value doesn't change by declaring final to such a constant. It will
improve code readability.
Not Recommended Sample
Recommended Sample
public class FixedSample {
variable will cause performance and code readability decrease and multithread become inconsistent.
Use instance variable after considering its necessity.
Not Recommended Sample
Recommended Sample
public class FixedSample {
value = inValue.getData();
//process
//process
}
}
}
}
Updated
3/9/2006
By
By
60/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
61/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
62/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
is already initialized is performed.
Sample
[Initialization in constructor]
public class Sample1{
private String name;
public Sample1 {
name = "suzuki" ;
}
public String getName() {
return name;
}
}
[Initialization on instance variable declaration]
public class Sample2{
private String name = "suzuki";
public Sample2 {
}
public String getName() {
return name;
}
}
[Initialization in the first time getter method is accessed]
public class Sample3{
private String name ;
public Sample3 {
}
public String getName() {
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
63/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
if (name == null) {
name = "suzuki";
}
return name;
}
}
The idea of encapsulation in object oriented is it is not desirable that everyone can access internal
state of the class. Define set/get method properly, access instance variable through that method.
Not Recommended Sample
Recommended Sample
public class FixedSample {
}
}
System.out.println(sample.value);
Updated
3/9/2006
By
By
64/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
65/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
an array is declared as final, the size is unchangeable, but the element is changeable. If you
want that the element is unchangeable, generate read-only collection using Collection class method
unmodifiableList().
Not Recommended Sample
Recommended Sample
import java.util.*;
= {0, 1, 2, 3};
Isn't object name used when accessing class variable? Use class name when accessing class
variable. By following this rule, code readability will improve.
Not Recommended Sample
Recommended Sample
public class FixedSample {
}
}
}
}
Updated
3/9/2006
By
By
66/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
67/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
If place where variable declared is separated away from place where variable used, it will cause
code readability and maintainability decrease. To prevent this, declare local variable right before
use it.
Not Recommended Sample
Recommended Sample
public class FixedSample {
..
int localValue2 = 20;
test.sampleMethod1(localValue1);
test.sampleMethod2(localValue2);
..
..
test.sampleMethod2(localValue2);
..
test.sampleMethod3(localValue3);
test.sampleMethod3(localValue3);
..
..
}
}
}
}
Updated
3/9/2006
By
By
68/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
new local variable for each role. As a result, code readability and maintainability will improve, and
the optimization of compiler can be achieved.
Not Recommended Sample
Recommended Sample
public class FixedSample {
int i;
int total = a * 2
i=a*2
}
}
}
}
Updated
3/9/2006
By
By
69/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
70/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Created
Title
A.3.14. Inheritance
C_IHT001 Do not override instance variable of super class in sub class
Isn't the field of the same name as a super-class declared in the subclass? When the field of the
Explanation /
Motive
same name is declared, the field of a super-class is hidden by the field declared in the subclass.
Do not create duplicated name, because it will confuse other people.
Not Recommended Sample
Recommended Sample
public class FixedSample{
new BadSample().print();
new FixedSample().print();
}
private void print(){
System.out.println( "number is " + number );
System.out.println("super.number is "+
super.number );
System.out.println("childNumber is "+
childNumber);
}
number is 5
super.number is 4
Updated
3/9/2006
By
By
71/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
Recommended Sample
sampleMethod();
sampleMethod();
C_IHT003 Do not define method in sub class which has the same name with private method in super class
Do not define method in sub class which has the same name with private method in super class.
Private method will not be overridden, and will be treated as different method. It will confuse other
Explanation /
Motive
Do not modified public method of super class to private method incorrectly. If that method is overriden in subclass, the meaning of subclass method will change. It will not become an error,
so it can be a bug without we realize it.
Explanation
Updated
3/9/2006
By
By
72/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
parentInstance.sampleMethod ();
}
}
Class which inherit super class
public class Child extends Parent {
public void sampleMethod(){
System.out.println("Child: method");
}
}
If method overriding is performed correctly, when the method which its argument defined as super class type is
invoked, automatically the method in subclass is called.
Therefore, is above program is executed, Child class method sampleMethod is invoked because ParentClass
method sampleMethod is overridden in Child class. The result is like the following.
Child: method
On the other hand, method which is declared as private in super class can not be overridden. It will not cause
any error, but is treated as different method.
If sampleMethod in ParentClass is declared as private, the result is :
Parent: method
Because method is not overriden, sampleMethod of ParentClass is called. It will be the cause of bug if we change
it carelessly
Updated
3/9/2006
By
By
73/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
C_IHT004 Implement both equals() method and hashCode assuming to store object in Collection class.
When we override Object.equals() method, do we also override Object.hashCode() method?
According to the specification of java.lang.Object, objects judged as equals by equals() method,
should return same value in hashCode() method. The same thing can be said in case of oppositely.
Explanation /
Motive
If this agreement is violated, this method will not work properly if object is used in collection based
on Hash such as HashMap, HashSet, and HashTable.
If you override one of equals() or hashCode() method, do override another one.
Example
Look the example of implementation of equals() and hashCode() methods in class IDNumber. The equals() method
below will return true if the value of attribute id is equal
public final class IDNumber {
private final int id;
public IDNumber(int id){
this.id = id;
}
public boolean equals(Object object){
boolean isEqual = false;
if (object == this) {
isEqual = true;
} else if (object instanceof IDNumber){
IDNumber idNum = (IDNumber)object;
if (idNum.id == this.id) {
isEqual = true;
}
}
}
}
The above class IDNumber only overrides equals() method. In this state, we use class IDNumber in HashMap.
Map map = new HashMap();
map.put( new IDNumber(123), "Hanako" );
Updated
3/9/2006
By
By
74/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Seemingly, if map.get(new IDNumber(123)) is executed for this HashMap, it seems to be able toget "Hanako".
However , the returning value is null.
With the default hashCode() method, even if id value is the same, when new hash is created another hash
code is given to that instance. In the example above, new instance is created when getting the content
of HashMap. Therefore, different hash code is given even if id value is the same, and it is recognized as
another instance of IDNumber . To avoid this problem, override hashCode() method.
Override hasdCode() method carefully. The same instance must return same hash code. Below is the example of
hash code method.
public int hashCode() {
int result = 13; // prime number
result = 171 * result + id;
return result;
}
We gave an example to implement hashCode() method. There are many ways of implementing this method,
By overriding hashCode() method and implementing it to return correct value, we can get correct result when using
collection class based on hash.
C_IHT005 Implement toString() method as far as possible
Have you checked that you obtain the value expected using toString() method ? The default of
Explanation /
Motive
Recommended Sample
public class FixedSample{
sampleValue = value;
}
public static void main(String[] args){
System.out.println(
}
sampleValue = value;
}
new BadSample(100));
Updated
3/9/2006
By
By
75/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
result.append(sampleValue);
result.append("]");
result
return result.toString();
BadSample@5224ee
Created
A. Java Coding Convention
}
public static void main(String[] args){
System.out.println( new FixedSample(100));
}
}
If we execute above program, we get the following
result
FixedSample(100)
Updated
3/9/2006
By
By
76/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.15. Instance
C_IST001 Use equals() method to compare objects
Don't you use "==" to compare objects? If we use "==", we are not comparing if the objects value
is same, but comparing if they are the same instances or not. Use equals() method to compare
Explanation /
Motive
objects value.
The default of equals() method is simply "==" comparison. Then the suitable comparison of each
object is implemented by overriding this method. For instance, to compare whether the character
string value stored in String is equal, the equals() method of the String class is implemented.
Not Recommended Sample
Recommended Sample
public class FixedSample {
if( left.equals(right) ){
} else {
} else {
}
}
}
}
Updated
3/9/2006
By
By
77/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
There is a possibility that two or more different classes has the same value because the package
name is not attached to the return value of the getName() method depending on Java VM.
Because the package name is attached in the getName() method of JDK 1.4, the name is unique
Not Recommended Sample
Recommended Sample
import java.util.*;
import java.util.*;
ClassclassA =sampleList.getClass();
return classA.equals(classB);
}
}
return classAName.equals(classBName);
}
}
Updated
3/9/2006
By
By
78/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
It becomes difficult to know where the process stops. Put "{}" to prevent bug caused by forgetting
to put "{}" when adding new process.
Not Recommended Sample
Recommended Sample
if (flag)
if (flag) {
System.out.println("Inside IF")
System.out.println("Inside IF")
System.out.println("Outside IF")
System.out.println("Inside IF")
}
}
C_CTR002 Do not use block {} which does not contain any statement
Write statement within if/for statement. in the if sentence and the for sentence. While developing,
Explanation /
Motive
Updated
3/9/2006
By
By
79/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Created
Title
In many cases, it is mistaken with "==" , or substitution that should be done outside conditional
statement is performed in conditional statement. It can be compiled if variable substitute in "=" is
boolean type, but will cause compiling error in other types of variable.
Not Recommended Sample
Recommended Sample
public class FixedSample{
String value = 0;
String value = 0;
if (flag = true) {
if (flag == true) {
value = a;
value = a;
return value;
return value;
In the parenthesis of for statement, we write counter declaration, loop condition and expression to
find next counter. If we omit these condition, then we should consider to use while statement.
Only use for statement with conditional expression omitted if there is a clear reason.
Not Recommended Sample
Recommended Sample
counter.
Updated
3/9/2006
By
By
80/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
int i = 0;
for (; i < x; ) {
i++;
Created
A. Java Coding Convention
System.out.println(arrayStr[i]);
}
}
import java.util.StringTokenizer;
int i = 0;
StringTokenizer strToken =
i++;
new StringTokenizer(target);
while(strToken.hasMoreTokens()){
System.out.println( strToken.nextToken());
}
}
Updated
3/9/2006
By
By
81/163
Teguh
Phase
Project Name
Block Name
Document Name
Function Name
Coding Conventions
C_CTR005
Page
Title
Created
A. Java Coding Convention
Explanation /
Motive
changed outside the conditional expression. It becomes easy to make mistake and difficult to find
it because control structure is difficult to understand.
Not Recommended Sample
Recommended Sample
public class FixedSample{
int badSampleMethod(){
int fixedSampleMethod(){
int result = 0;
int result = 0;
i += 1;
result += (2 * i 1);
result += i;
return result;
return result;
}
}
}
}
C_CTR006 The counter of the for statement is started from 0.
Please give 0 as an initial value of the counter used in the for statement unless there is a special
Explanation /
Motive
reason to use another initial value. For instance, code readability will drop if starting value other
than 0 is used in for statement when accessing members of array.
Not Recommended Sample
Recommended Sample
public class FixedSample {
testArray[i-1] = i;
testArray[i-1] = i;
}
}
}
}
Updated
3/9/2006
By
By
82/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Explanation /
Motive
Please use neither break nor continue as much as possible to simplify control structure and
improve code readability.
Not Recommended Sample
Recommended Sample
public class FixedSample{
sample.useContinue();
sample.unUseContinue();
sample.useBreak();
sample.unUseBreak();
int skipNumber = 5;
int skipNumber = 5;
if ((i + 1) == skipNumber){
if ((i + 1) != skipNumber){
continue;
System.out.println(i + 1) ;
System.out.println(i + 1);
}
private void useBreak(){
int limitNumber = 5;
int limitNumber = 5;
if (limitNumber < (i + 1) ){
System.out.println(i + 1);
break;
}
System.out.println(i + 1) ;
}
}
}
}
Updated
3/9/2006
By
By
83/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
}
Execution Result
Execution Result
10
10
copying process by ourselves will be a waste, prone to error and decrease the execution speed.
Use System.arraycopy instead.
Not Recommended Sample
Recommended Sample
public class FixedSample{
String[] copy(String[] orgArray){
if(orgArray == null){
return null;
return null;
Updated
3/9/2006
By
By
84/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
System.arraycopy(orgArray, 0,
copyArray[i] = orgArray[i];
copyArray, 0, length);
return copyArray;
return copyArray;
drop, because much time is required to generate object. To avoid this problem, create instance
outside loop, and reuse it.
Not Recommended Sample
Recommended Sample
public class FixedSample {
StringBuffer sampleBuffer =
StringBuffer sampleBuffer =
new StringBuffer();
new StringBuffer();
sampleBuffer.append("log: ");
sampleBuffer.append("log: ");
sampleBuffer.append(array[i]);
sampleBuffer.append(array[i]);
System.out.println(
System.out.println(
sampleBuffer.toString());
sampleBuffer.toString());
sampleBuffer.setLength(0);
}
}
Updated
3/9/2006
By
By
85/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Avoid using if, else, and switch as far as possible, and use the technique of object oriented
C_CTR010
Aren't there many branch in a method? Code readability will drop and code will be difficult to
Explanation /
Motive
maintain if it contains many switch, if/else statements. This is a problem of design, consider to use
polymorphism, FactoryMethod, Prototype, and State pattern. Below is the sample of polymorphism.
Not Recommended Sample
Recommended Sample
animals[i].cry();
((Dog)animals[i]).bark();
}
}
public abstract class Animal{
}
}
}
public class Dog {
System.out.println("Woof woof");
System.out.println("Woof woof");
System.out.println("Meow meow");
}
System.out.println("Meow meow");
}
Updated
3/9/2006
By
By
86/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Explanation /
Motive
[Exception]
If we want to execute process until the end of the loop even if exception is occurred.
Not Recommended Sample
Recommended Sample
public class FixedSample{
try {
try {
someOtherMethod(num);
someOtherMethod(num);
catch(NumberFormatException e) {
catch(NumberFormatException e) {
e.printStackTrace();
e.printStackTrace();
}
}
}
}
Updated
3/9/2006
By
By
87/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
88/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.17. Thread
C_TRD001 Implement Runnable for thread
There are two methods of implementing thread
1. Create subclass of Thread
2. Implement Runnable interface
Adopt the method of implementing Runnable interface to create thread. For instance, we have
program to move Radio Controlled Car. Controller object and Car object run in different thread,
Explanation /
Motive
and these object must be declared as Controller class with the function of controller, and
Car class with the function of car. These classes may have thread function, but should not be
declared as subclass of Thread.
Java does not support multiple inheritances. If those classes inherit Thread class, they cannot
inherit another class. Do not inherit Thread class except we want to extend basic function of
Thread (other than run() method)
Not Recommended Sample
Recommended Sample
implements Runnable{
car = _car;
car = _car;
car.startEngine();
//
car.startEngine();
//
}
}
Updated
3/9/2006
By
By
89/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
notify() method. But we can not predict which thread is resumed. Therefore there is a possibility
that thread should be resumed is not resumed. To avoid this, use notifyAll method() to resume all
threads which are in waiting state, if the following assumptions do not exist.
1. There is only one thread in waiting state.
2. All the waiting thread have the same condition (when which thread may be called)
Not Recommended Sample
Recommended Sample
public class FixedSample {
synchronized(car){
synchronized(car){
fuel = _fuel;
fuel = _fuel;
car.notify();
car.notify();
} // ...
} // ...
if you call Thread.yield() method. Furthermore, it also can not be assured that the control will
moves to other threads. Design without using Thread.yield() for process which operation
afterward should be assured. Lock that thread has is not released by yield() method. An
unexpected operation will occurs if yield() method is called when thread is locked. If you want
to switch thread when it is locked, use wait() method of locked object.
Not Recommended Sample
Recommended Sample
Updated
3/9/2006
By
By
90/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
synchronized(lock){
synchronized(lock){
Thread.yield();
try {
lock.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
C_TRD004 Do not call a method which has synchronized block from synchronized block
Do not call method which has synchronized block from synchronized block. You should consider
that there is a possibility of deadlock occurs. There is a possibility of deadlock occurs if
the following conditions are met :
1. There are multiple lock objects
2. Go to lock another object without releasing current lock object
Explanation /
Motive
Deadlock is a state where two threads exist and each other is waiting for the other thread to release the object
they lock.
For example, assume that there are two cooks. To work, both need knife and cutting board, but there are only
one knife and one cutting board. Cook A took the knife and cook B took the cutting board. But they cannot perform
Updated
3/9/2006
By
By
91/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
job because they need both knife and cutting board. Therefore cook A waits cook B to give away his cutting board,
and cook B waits for cook A to give away his knife persistently. They will end up waiting forever, and can not
do the job.
Below is an image of thread A (cook A) and thread B (cook B) is waiting each other for releasing resources of
X (knife) and Y (cutting board)
Thread A (Cook A)
X (Knife)
1. Access synchronized
to Y
1. Access synchronized
to X
2. Access synchronized
to Y
Thread B (Cook B)
Y (Cutting
Board)
2. Access synchronized
to X
This problem can be solved if access order to lock objects is set. For example, we decide rule "Knife must be
taken first". If cook A take knife first, the cook B must wait cook A finishing his job and releasing the knife.
After cook A finishing his work cook B can take the knife, therefore deadlock will not occur.
Recommended Sample
public class FixedSample{
public static void main(String[] args){
try{
synchronized(test){
test.wait();
} catch(InterruptedException e){
e.printStackTrace();
}
try{
test.wait();
} catch(InterruptedException e){
e.printStackTrace();
Updated
3/9/2006
By
By
92/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
}
}
}
in certain condition. There is a possibility that the assumption of the condition breaks when
wait() method is called excluding the while block.
Not Recommended Sample
synchronized(car){
Recommended Sample
synchronized(car){
if (fuel == null){
try{
try{
car.wait();
car.wait();
}catch(InterruptedException e){
}catch(InterruptedException e){
e.printStackTrace();
e.printStackTrace();
car.drive();
car.drive();
if to while.
Updated
3/9/2006
By
By
93/163
Teguh
Phase
Project Name
Block Name
Document Name
Function Name
Coding Conventions
Page
Created
Title
while (<condition>) {
//process
//process
}
The occupation time of process becomes long even when inquiry is done after certain period of
time. After first inquiry, next process cannot be executed until the next inquiry is performed, even
if the condition is satisfied.
If we set the thread so that wait() method is called when condition is not satisfied, and notifyAll()
method is called when condition is satisfied, the wasteful inquiry is not required.
Not Recommended Sample
Recommended Sample
Updated
3/9/2006
By
By
94/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
synchronized(controller){
synchronized(controller){
try{
try{
Thread.sleep(10000);
controller.wait();
}catch(InterruptedException e){
}catch(InterruptedException e){
e.printStackTrace();
e.printStackTrace();
this.processCommand(commands[i]);
this.processCommand(commands[i]);
commands = null;
commands = null;
this.commands = commands;
this.commands = commands;
//
//
}
}
Created
}
}
Updated
3/9/2006
By
By
95/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Robot.storeCommands(commands);
However, until this process is performed, every 10000
Robot.storeCommands(commands);
controller.notifyAll();
synchronized (<instance>) {
}
}
The instance to take the lock is written in <instance> part of 2. Synchronized block.
Then, of what 1.synchronized method takes the lock? The method 1 has the equal meaning
with the following
void method() {
synchronized (this) {
}
Explanation /
Motive
Updated
3/9/2006
By
By
96/163
Teguh
Phase
Project Name
Block Name
Document Name
Explanation /
Motive
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
The synchronized method takes the lock of this (In case of static synchronized method,
java.lang.Class instance of that class will be locked).
If lock is performed against this, synchronized method of the same object can not be called
because locked object can not be synchronized accessed. This may be a thread safe,
however method which may not be synchronized must wait until the lock is released.
Put in the mind that lock against this can cause width-range effect.
Therefore, first consider that whether a partial lock can be achieved in the synchronized block
declare the method in synchronized only when it is judged that synchronization is necessary
of the entire method.
When synchronized block is used, the scope of synchronization should be as minimal as possible.
By minimalizing the range applicable scope of synchronization, we can avoid following risks :
1. Deadlock occurrence
2. Performance decrease
3. Debug cost if deadlock occurs
Not Recommended Sample
public class BadSample {
Recommended Sample
public class FixedSample {
this.name = name;
synchronized(this.name){
this.name = name;
birthday = day;
synchronized(birthday){
birthday = day;
called
}
}
}
Updated
3/9/2006
By
By
97/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
98/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
instance or not. Therefore, use equals() method of String class to compare strings.
In case of literal, if the content is the same, the result of comparison using "==" or using equals()
will be same because compiler will optimize those to the same instance. However, follow this rule
in code.
Not Recommended Sample
Recommended Sample
public class BadSample {
String anotherName){
String anotherName){
return name.equals(anotherName);
Java VM in each case instance will be generated, and it will consume extra memory. It is not
necessary to use new for string constant.
Not Recommended Sample
Recommended Sample
public class FixedSample {
System.out.println(sampleString);
System.out.println(sampleString);
}
}
}
}
Updated
3/9/2006
By
By
99/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
with another one, the object will be recreated. It will lead to performance decrease. Define as
StringBuffer for character string that can be modified, and use append() method of StringBuffer
to concatenate strings
Not Recommended Sample
Recommended Sample
public class FixedSample {
fruit += , bananas;
fruit.append(apples);
return fruit;
fruit.append(, bananas);
return fruit.toString();
}
}
Do you define fixed character string as StringBuffer? The performance will improve if String
object is used for string constant, because memory operation is not performed.
Not Recommended Sample
Recommended Sample
public class FixedSample {
StringBuffer buffer
= new StringBuffer(Message);
System.out.println(output);
}
}
Updated
3/9/2006
By
By
100/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
C_STR005 When comparing string literal with variable, use equals() method of string literal
When comparing strings using equals method(), it is possible to use String object.equals(literal)
or string literal.equals(String object). In the former, it is necessary to check whether string is null
Explanation /
Motive
or not before calling equals() method. In the latter, it is not necessary to check null because
it is already known that string literal is not null. Therefore use string literal.equals(String object)
for comparing strings.
Not Recommended Sample
Recommended Sample
public class FixedSample {
return y.equals(userInput);
&& userInput.equals(y);
}
}
}
}
C_STR006 Use conversion method to convert String object to primitive type or vice versa
Explanation /
Motive
There are various methods in conversion of String type and a primitive type. The most efficient
and comprehensive way is to use conversion method.
Not Recommended Sample
Recommended Sample
Updated
3/9/2006
By
By
101/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
startsWith() method is used if the argument is multiple characters. startsWith() method can be
used with one character argument, however this is misuse of String API.
If you replace startsWith() with charAt(0), check if the length of string is at least one.
Not Recommended Sample
Recommended Sample
public class FixedSample {
return (checkString.startsWith(E);
}
}
as \n, \r is used as line feed code (One of java feature [Write once, run anywhere] will be lost)
If you want to use line feed code, use system.getProperty() to get line feed code corresponding
to the system.
Not Recommended Sample
Recommended Sample
public class FixedSample {
StringBuffer result =
StringBuffer result =
new StringBuffer(Message:n);
new StringBuffer(Message:);
result.append(message);
result.append(System.getProperty(
System.out.println(result);
line.separator));
result.append(message);
System.out.println(result);
}
}
Updated
3/9/2006
By
By
102/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
103/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
A.3.19. Number
C_NUM001 Use BigDecimal class for calculation without error margin
Is the calculation result within assumed error margin obtained? The floating point arithmetic is used
for the science and technology calculation, and the error margin occurs. On the other hand,
Explanation /
Motive
because class BigDecimal calculates the numerical value by the character string, it is suitable
for an accurate calculation of the amount of money etc. Precision in the number of digits specified
when the instance is generated is guaranteed in BigDecimal.
Sample
Updated
3/9/2006
By
By
104/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
A. Java Coding Convention
in the floating point calculation as explained in the former rule. It can not be guaranteed that
assumed result can be obtained when comparing this number with another one.
Not Recommended Sample
Recommended Sample
System.out.println("value=100");
} else {
comparing number.
System.out.println("value!=100"); }
}
}
C_NUM003 Do not cast a number to primitive type with low precision.
In primitive type variable which represent number, the precision of that number is defined. When we
Explanation /
Motive
cast high precision of variable into low precision type, the precision of the value will be changed to
the precision of type to which we cast. Therefore there is a possibility that error margin occurs.
Sample
Updated
3/9/2006
By
By
105/163
Teguh
Phase
Project Name
Block Name
Document Name
int : 2
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
106/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.20. Date
C_DATE001
Do you have a perception of using Date type of array to handle array of date ? Date instance
Explanation /
Motive
consumes more resources compared to other instance. Therefore, if you just handle a simple date,
unnecessary resources will be consumed. Use long type of array instead Date type of array
to improve the performance.
Not Recommended Sample
import java.util.*;
Recommended Sample
public class FixedSample {
int length = 3;
int length = 3;
times[i] = System.currentTimeMillis();
System.out.println(times[i]);
dates[i] = now.getTime();
}
}
}
}
left sample)
Execution result
1078115074691
1078115074691
1078115074701
1078115074701
1078115074701
1078115074701
Explanation
Explanation
System.getCurrentTimeMillis()
of Date class
cal.setTimeInMillis(time);
Updated
3/9/2006
By
By
107/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Date date = cal.getTime();
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
108/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.21. Collection
C_CLT001 Use collection class of Java 2 or later.
Do you use Vector class, HashTable class and Enumeration class ? If there is not any special
reason to use those classes, use List (ArrayList class), Map (HashMap class) and Iterator in
Explanation /
Motive
order to standardize interface. By using interface such as List, we can use easy-to-understand
method organized in JDK1.2. As the characteristic of interface, we can change implement class
without changing the invoker.
Not Recommended Sample
Recommended Sample
import java.util.*;
import java.util.*;
sampleVector.addElement(1);
sampleList.add(1);
sampleVector.addElement(2);
sampleList.add(2);
sampleVector.addElement(3);
sampleList.add(3);
Enumeration sampleEnumeration =
sampleVector.elements();
while (sampleIterator.hasNext()) {
while (sampleEnumeration.
System.out.println( sampleIterator.next());
hasMoreElements()) {
System.out.println(
sampleList.remove(1);
sampleEnumeration.nextElement());
sampleVector.removeElement(1);
System.out.println( sampleList.get(i));
}
}
Updated
3/9/2006
By
By
109/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
}
C_CLT002 Use collection class that only accepts specific type of object
We can newly define collection class which only stores specific type of object. For instance, we
can define collection class that only stores String object.
Advantages of defining such a collection class are
Explanation /
Motive
1. ClassCastException does not occur because different type of object can not be stored
2. Class casting is not necessary when taking the object out of collection ( The check logic
of instanceof is also not necessary)
From the above-mentioned, the possibility of bug can be decreased, code becomes simple and
its readability will improve.
Sample
Updated
3/9/2006
By
By
110/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
111/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.22. Stream
C_STM001 Do post-handling in finally block when using API which handle stream
Is close() method surely executed in stream? To avoid memory leak, closing a stream is mandatory.
Explanation /
Motive
Write close() method in finally block so that stream will certainly be closed even if exception
is thrown midway.
Not Recommended Sample
Recommended Sample
try {
reader.read();
try {
reader.close();
new FileReader(file));
fnfe.printStackTrace();
reader.read();
ioe.printStackTrace();
fnfe.printStackTrace();
ioe.printStackTrace();
} finally {
try{
reader.close();
} catch (IOException ioe2) {
ioe2.printStackTrace();
}
}
}
}
Updated
3/9/2006
By
By
112/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
a possibility that OutOfMemoryError is generated when a lot of objects are written with the
ObjectOutputStream object without calling the reset() method.
Exception : Do not use reset() method when writing the same object repeatedly in stream, because
function to cache object by stream is used to fasten access speed.
Not Recommended Sample
Recommended Sample
public classFixedSample {
throws IOException {
throws IOException {
ObjectOutputStream stream =
ObjectOutputStream stream =
FileOutputStream("output"));
FileOutputStream("output"));
stream.writeObject(input);
stream.writeObject(input);
stream.reset();
}
}
Updated
3/9/2006
By
By
113/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
114/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.23. Exception
C_EXT001Use detail class for catching exception
Do you use Exception, RuntimeException and Throwable etc in catch statement ? If super
class is used for catching exception, proper handling according to kind of exception cannot be
done in catch block. There is also a possibility that exception should be thrown in invoker is
Explanation /
Motive
caught. Always use subclass of Exception, RuntimeException and Throwable for exception
handling.
Exception : There is no problem if these classes are used for the last exception handling.
Not Recommended Sample
Recommended Sample
import java.io.*;
import java.io.*;
try {
try {
reader = new BufferedReader(
new FileReader(file));
new FileReader(file));
reader.read();
reader.read();
} catch (Exception e) {
e.printStackTrace();
fnfe.printStackTrace();
} finally {
try{
ioe.printStackTrace();
reader.close();
} finally {
try{
e2.printStackTrace();
reader.close();
ioe2.printStackTrace();
}
}
Updated
3/9/2006
By
By
115/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
}
C_EXT002 Do not create and throw an object of Exception class
Don't you create object of Exception class and throw it ? Exception class is super class
Explanation /
Motive
of all exception. In code which catch instance of Exception class as exception, polymorphism
can not be used for that kind of exception. Throw a proper subclass object.
Not Recommended Sample
Recommended Sample
public class FixedSample {
throws NoSuchMethodException {
}
}
processed in catch block. If it can not be handled, then output log etc so that we can check if
exception occurs.
Exception : We want to use catch block but intentionally not write exception handling.
Not Recommended Sample
Recommended Sample
import java.io.*;
import java.io.*;
try {
try {
reader = new BufferedReader(
new FileReader(file));
reader.read();
Updated
3/9/2006
By
By
116/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
fnfe.printStackTrace();
} catch (IOException ioe) {
} finally {
} finally {
try{
try{
reader.close();
reader.close();
ioe2.printStackTrace();
}
Exception and Error class. The meaning of error and exception become vague if exception of
application is inherited from this class.
As written above, Error class should not be inherited in application. Similarly, Throwable class
should not be inherited in application. Exception defined in application should extend Exception
class.
Not Recommended Sample
Recommended Sample
public class FixedSampleException
extends Exception {
Updated
3/9/2006
By
By
117/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Explanation /
Motive
package. Moreover, when defining new exception, define one so that it can be used in entire
application, not only be used in specific method.
Not Recommended Sample
Recommended Sample
extends Exception {
public SampleClassABCMethodException(
String sample) {
super(sample);
}
}
C_EXT006 finally block is certainly executed.
No matter exception is caught or not, statement written in finally block is certainly executed. In finally
Explanation /
Motive
block, write process that certainly should be performed such as stream closing process. Do not
write return statement or statement that affects the return value of method in finally block.
Not Recommended Sample
Updated
3/9/2006
By
By
118/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
}
}catch(SampleException e){
e.printStackTrace();
}finally{
a = 2;
}
return a; // this method's return value is 2
}
}
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
119/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
120/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
Java VM to perform necessary process when objects disappear. If you override this method
without explicitly call super.finalize() method, finalize() method of super class will not be
executed and necessary process will not be performed.
Not Recommended Sample
Recommended Sample
public class FixedSample {
super.finalize();
}
}
Depending on the process in finalize() method, there is a possibility that inconsistency occurs if
finalize() method is called twice. It can cause bugs, therefore do not call finalize() method from
application.
Not Recommended Sample
Recommended Sample
import java.io.*;
import java.io.*;
if(stream != null){
stream.close();
}
super.finalize();
}
Updated
3/9/2006
By
By
121/163
Teguh
Phase
Project Name
Block Name
Document Name
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
released = true;
sample.finalize();
release();
sample = null;
super.finalize();
}
}
Page
}
}
public class FixedTest {
private FixedSample sample =new FixedSample ();
void closeTest() throws Throwable {
sample.release();
sample = null;
}
}
Updated
3/9/2006
By
By
122/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
123/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
A.3.25. Others
C_MISC001Implement Cloneable explicitely
Do you implementing Cloneable interface when using clone() method? Clone method is supported
Explanation /
Motive
Recommended Sample
public class FixedSample implements Cloneable{
try{
try{
return super.clone();
return super.clone();
}catch(CloneNotSupportedException e){
}catch(CloneNotSupportedException e){
sample.clone();
sample.clone();
}
}
}
}
Updated
3/9/2006
By
By
124/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
A. Java Coding Convention
If class which doesn't have inheritance relation is included in casting objects, check using
instanceof.
Not Recommended Sample
Recommended Sample
public class FixedSample {
}
}
}
Updated
3/9/2006
By
By
125/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
A. Java Coding Convention
Updated
3/9/2006
By
By
126/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
: TOPS
* Client Name
: TOYOTA
* Program Id
: BTOPSL01.pc
* Language
* Author
: Ajay K P
* Version
: 1.00
* Creation Date
: 2005/12/20
*
* Update history
* XX.XX.XX
Refix date
20001013
Person in charge
XXXXX
Description
XXXXXXXXXXXXXXXXXX
*
* Copyright(C) 2002-TOYOTA Motor Corporation. All Rights Reserved.
*************************************************************************************************/
Created
B. Batch Coding Convention
Updated
3/9/2006
By
By
127/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
*/
/******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sqlca.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <ctype.h>
#include <float.h>
#include <varargs.h>
/******************************************************************************/
/* GSCM Batch Frame-work header files. It used for (Pre-process/Get parameter */
/* process, loging process and Post Process ).
*/
/******************************************************************************/
#include <PZS1101.h>
/******************************************************************************/
/* Application header files.
*/
/******************************************************************************/
#include <BTOPS001.h>
#include <BTOPS002.h>
#include <BTOPS003.h>
Created
B. Batch Coding Convention
Updated
3/9/2006
By
By
128/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
B. Batch Coding Convention
Updated
3/9/2006
By
By
129/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
*/
/******************************************************************************/
FILE_TYPE gs_FileInfo;
FILE
* gfp_Data = NULL;
gs_InvDt[9];
int
gn_JobStatusFlag = 0 ;
int
gn_UploadOperation;
char
gs_FilePath[SIZE_PATH + 1];
char
gs_CurrInvFlag[2];
char
gs_InvFlagToInsert[2];
char
gs_CurrRecord[ED_REC_LEN + 1];
*/
/********************************************************************************/
extern char xs_SubmitTm[]; /* Submit Time to be used in updProcCtrl */
extern int
xn_PID
*/
*/
Created
B. Batch Coding Convention
Updated
3/9/2006
By
By
130/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
B. Batch Coding Convention
Updated
3/9/2006
By
By
131/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
C. SQL Coding Convention
3/9/2006
Updated
By
By
132/163
Teguh
Phase
Block Name
Example)
SELECT T1.LASTNAME,
T2.NAME,
MAX(T3.SALARY) BEST_SALARY
FROM EMPLOYEE T1,
COMPANY T2,
SALHISTORY T3
WHERE T1.COMPANYID
= T2.COMPANYID
Project Name
TMAP Application Standard
AND T1.EMPID = T3.EMPID
TMAP
Development
Standard
Function Name
AND T1.HIREDATE > ADD_MONTHS(SYSDATE,
-60).....;
Coding Conventions
Title
d.
e.
Confirm the execution plan to determine the order of the table association.
f.
Reserved words for nodes in DML statements should be aligned to the right.
Page
Created
C. SQL Coding Convention
Updated
3/9/2006
By
By
133/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
Created
C. SQL Coding Convention
3/9/2006
Updated
b.
c.
An ORDER BY and GROUP BY clause should not target any non-key fields.
An ORDER BY and GROUP BY should be carried out on the key fields.
When unavoidable, monitor the performance and request for index configuration if necessary.
d.
e.
By
By
134/163
Teguh
Phase
Project Name
Block Name
Document Name
f.
Page
Function Name
Coding Conventions
Title
Created
C. SQL Coding Convention
Updated
HAVING clause
Use a WHERE clause for a selection operation where possible.
Use HAVING only when specifying a selection condition against the result from a set operation such as BY.
g.
h.
i.
WHERE PARTSNUM != 0
- If anything else but a front concordance is specified in a part concordance search using a LIKE operator
<Use of index>
Obtain and valuate the execution plan because the usage of indexes changes by various conditions.
j.
k.
3/9/2006
By
By
135/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
C. SQL Coding Convention
Updated
External association
Pro*C/C++ R9.2.0 and Pro*COBOL R9.2.0 do not support ANSI association syntax as an embedded SQL statement.
o.
p.
q.
3/9/2006
By
By
136/163
Teguh
Phase
Project Name
Block Name
Document Name
r.
Page
Function Name
Title
Created
C. SQL Coding Convention
Updated
3/9/2006
By
By
137/163
Teguh
Phase
Project Name
Block Name
Document Name
Coding Conventions
Page
Function Name
Title
Created
C. SQL Coding Convention
Updated
b.
c.
d.
b.
c.
d.
3/9/2006
By
By
138/163
Teguh
Phase
Project Name
Block Name
Document Name
Page
Function Name
Coding Conventions
Title
: TOPS
# * Client Name
: TOYOTA
# * Program Id
: BTOPSL01.ksh
# * Language
# * Author
: Ajay K P
# * Version
: 1.00
# * Creation Date
: 2005/12/20
#*
# * Update history
# * XX.XX.XX
Refix date
20001013
Person in charge
XXXXX
Description
XXXXXXXXXXXXXXXXXX
#*
# * Copyright(C) 2002-TOYOTA Motor Corporation. All Rights Reserved.
# *************************************************************************************************
Created
D. Shell Script Coding Convention
Updated
3/9/2006
By
By
139/163
Teguh
Phase
Block Name
Document Name
Project Name
Page
Function Name
Title
Created
D. Shell Script Coding Convention
Updated
3/9/2006
By
By
140/163
Teguh
***
---- NG!
---- OK!
->
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
ROLLBACK;
Pk_Logger.writeDetailToDB(.....
END;
END;
4.
->
CASE rec.ID
WHEN 'A' THEN product_code := 10;
WHEN 'B' THEN product_code := 20;
WHEN 'C' THEN product_code := 30;
ELSE
product_code := 40;
product_code := 30;
ELSE
product_code := 40;
END IF;
->
END CASE;
OR
product_code :=
CASE rec.ID
WHEN 'A' THEN 10
WHEN 'B' THEN 20
WHEN 'C' THEN 30
ELSE
40
END;
***
5. Use Index
<< When index is attached to COL. >>
select .... where COL * 10 = :VAL;
select .... where COL = :VAL / 100;
<< When the index consists of the following columns's sequence. >>
1) DEPT_CD
2) NAME
3) AGE
select .... where NAME = 'SMITH';
select .... where NAME = 'SMITH' and AGE = 25;
select .... where DEPT_CD = 1 or NAME = 'SMITH';
---- NG!(Does not use index, for not using first column.)
---- NG!
---- NG!(Does not use index, for using "or".)
select
select
select
select
select
-------------
....
....
....
....
....
where
where
where
where
where
OK!(Uses
OK!(Uses
OK!(Uses
OK!(Uses
index)
index)
index)
index)
CHECK SQL
->
Inex search
QUERY
------------------------------------------------------SELECT STATEMENT
COST=
2.1 TABLE ACCESS BY INDEX ROWID Z_TEST_TBL2
3.1 INDEX RANGE SCAN IX_Z_TEST_TBL2 NON-UNIQUE
CHECK SQL
QUERY
------------------------------------------------------SELECT STATEMENT
COST=
2.1 TABLE ACCESS FULL Z_TEST_TBL2
->
QUERY
6. Use ROWID
SELECT empno, sal FROM EMP
WHERE id = :id
FOR UPDATE NOWAIT;
:
:
->
***
7. Use CURRENT OF
DECLARE
CURSOR c1 IS SELECT empno, job, sal
FROM emp FOR UPDATE;
:
:
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO rec ...
...
UPDATE emp SET sal = new_sal
WHERE empno = rec.empno;
END LOOP;
->
DECLARE
CURSOR c1 IS SELECT empno, job, sal
FROM emp FOR UPDATE;
:
:
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO rec ...
...
UPDATE emp SET sal = new_sal
WHERE CURRENT OF c1;
END LOOP;
DECRARE
TYPE TYP_C1 IS TABLE OF TEST_TBL.C1%TYPE INDEX BY BINARY_INTEGER;
TYPE TYP_C2 IS TABLE OF TEST_TBL.C2%TYPE INDEX BY BINARY_INTEGER;
DECRARE
:
:
:
:
tbl_c1 TYP_C1;
tbl_c2 TYP_C2;
BEGIN
FOR i IN 1..10000 LOOP
tbl_c1(i) := i;
tbl_c2(i) := 'name-' || TO_CHAR(i);
END LOOP;
BEGIN
:
:
:
->
COMMIT;
COMMIT;
END;
END;
22 second
1 second
9. MERGE
Use "MERGE", when insert or update to table from other table.
ex) By emp_no TOTAL_SALE is inserted or updated.
TODAY_SALES
EMP_NO
1
2
4
SALES
10,000
20,000
30,000
->
MONTH_SALES
EMP_NO
1
2
3
SALES
210,000
100,000
340,000
->
MONTH_SALES
EMP_NO
1
2
3
4
CURSOR LOOP
CURSOR c1 IS SELECT * FROM TODAY_SALES;
BEGIN
FOR rec IN c1 LOOP
BEGIN
INSERT INTO MONTH_SALES
(EMP_NO, SALES)
VALUES(rec.EMP_NO, rec.SALES);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
UPDATE MONTH_SALES
SET SALES = SALES + rec.SALES
WHERE EMP_NO = rec.EMP_NO;
END;
END LOOP;
->
SALES
220,000
120,000
340,000
30,000
MERGE
MERGE INTO MONTH_SALES m
USING TODAY_SALES t
ON (m.EMP_NO = t.EMP_NO)
WHEN
MATCHED THEN UPDATE SET m.SALES = m.SALES + t.SALES
WHEN NOT MATCHED THEN INSERT (EMP_NO, SALES)
VALUES (t.EMP_NO, t.SALES);
tbl_c2(i));
Phase
External Design
Block name
Document name
Project name
C Common
SQL Standards
GSPS/A-TOP
Function name
Title
Common
SQL Standards
Created
Updated
2003/5/14
2003/11/05
2. SQL Standards
SQL standards are defined in the following table. In cases where it is not possible to adhere to the GSPS/A-TOP standards, the impact on areas such as response time should be investigated
and approval obtained from CIT.
TMC details of DB2 standards are provided in the document "Revised DB2 Standards.doc".
No. GSPS/A-TOPS standards
1 EXPLAIN check results
Where SQL has been chosen, EXPLAIN must be obtained in the stand-alone test phase to check
the access path.
The results of the EXPLAIN check should satisfy the following conditions.
<1> ACCESSTYPE=I (or I1)ACCESSTYPE=N requires DBA approval)
<2> MATCHCOLS0
<3> METHOD3 must conform to ORDER BY conventions (A-TOP standard No.11)
SQL is normally modified in order to change PREFETCH=L to either PREFETCH=S or 'None'.
<4> Any JOIN other than METHOD=1 (Nested Loop Join) must be approved by DBA
Where PLAN/PACKAGE is bound in the actual environment, the EXPLAIN(YES) option
must be used for BIND processing, to obtain and store access path information.
As per right-hand column
If there is only one applicable record (or less) and exclusion is not required following extraction
If there is only one applicable row (or less), use a single SELECT rather than FETCH.
used for BIND processing, to obtain and store access path information.
Where the same SQL statement is used more than one time in a program, rather than writing
UPDATE processing when there is only one applicable record (or less) should be performed directly
using single UPDATE.
Where UPDATE processing does not require cursor positioning, update directly using
a single UPDATE.
Where update can be performed based on the cursor, specify the 'FORUPDATEOF' in the
cursor declaration.
The COLUMN name for the UPDATE should be specified after the 'OF'.
The cursor used for DELETE is FOR UPDATE OF COL name 1
To obtain some rather than all applicable rows, specify OPTIMIZE for n ROWS.
Where column functions are used, these must be coordinated among individual applications
beforehand and CIT approval must be obtained.
Normally, only restricted column functions such as MIN, MAX and COUNT should be used.
MIN, MAX may only be used in the following cases:
<1> Where MIN, MAX can be obtained using ACCESSTYPE=I1
<2> Where DB2 searches 10 records or less in order to identify MIN, MAX
(e.g.: When finding the "latest data validity start time", all KEY items should be specified as
The use of column functions should be well considered and thoroughly discussed beforehand
among individual application development teams.
equal sign conditions in the WHERE clause, and there should be no more than 10
records with "different data validity start times".)
If COUNT is used, convention 1 must be satisfied.
External Design
Block name
Document name
Phase
Project name
GSPS/A-TOP
C Common
SQL Standards
Function name
Title
Common
SQL Standards
Created
Updated
2003/5/14
2003/11/05
11
12
13
Holding FETCH cursor across commit should be implemented using the SQL WITHHOLD clause
rather than by application program logic.
Use UNCOMMITEDREAD for read-only processes where practicable.
14
15
The UNION processing is not normally allowed. Where UNION is used, EXPLAIN results
must be obtained and submitted beforehand.
As per right-hand column
16
When joining multiple conditions using AND, start with conditions that have a higher filtering ratio.
17
When joining multiple conditions using OR, start with conditions that have a lower filtering ratio.
18
External Design
Block name
Document name
Phase
Project name
GSPS/A-TOP
C Common
SQL Standards
Function name
Title
Common
SQL Standards
Created
Updated
2003/5/14
2003/11/05
20
UNION processing is not normally allowed. Where UNION is used, EXPLAIN results must be
obtained and submitted beforehand.
OR join for non-equal sign predicate in same row is written with UNION.
SELECT * FROM TB1
WHERE A:HOSTVAR1 OR A:HOSTVAR2
-SELECT * FROM TB1
WHERE A:HOSTVAR1
UNION
SELECT * FROM TB1 WHERE A:HOSTVAR2
21
For UNION, DISTINCT is performed within DB2 to prevent duplicate rows being returned.
This should be avoided because SORT is executed for DISTINCT, increasing SQL costs.
For UNION ALL, DISTINCT is not performed, so where return of duplicate rows is not a problem,
UNION ALL is used.
OR join for equal sign predicate in same row is written with IN.
SELECT COUNT(*) FROM TB1
WHERE A='10' OR A='20' OR A='30'
22
LIKE description should be replaced with IN predicate or BETWEEN predicate wherever possible.
SELECT COUNT(*) FROM TB1
WHERE A LIKE 'IBM%'
-(where final part is between '1' and '9')
SELECT COUNT(*) FROM TB1
WHERE A IN('IBM1','IBM2','IBM3',
'IBM4','IBM5','IBM6','IBM7','IBM8',
'IBM9')
or
SELECT COUNT(*) FROM TB1
WHERE A BETWEEN 'IBM1' AND 'IBM9'
23
BETWEEN is used for range predicate; AND join of non-equal sign conditions is not used.
SELECT COUNT() FROM TB1
WHERE (A'100' AND A'200'
External Design
Block name
Document name
Phase
Project name
GSPS/A-TOP
C Common
SQL Standards
Function name
Title
Common
SQL Standards
25
The cursor used to extract records selected with SQL should be closed immediately when no longer required.
(This releases LOCKs where possible, and allows other programs waiting for LOCK to begin processing.)
26
Error checking should be performed on all SQL statements, including OPEN and CLOSE as well as FETCH and UPDATE/INSERT/SELECT.
27
The column name must be explicitly stated for SELECT process (SELECT * not allowed).
Specify only necessary fetch items to be obtained by the program using SELECT and UPDATE.
28
29
30
31
BETWEEN low-val AND high-val may not be used in 1st MATCHCOLS item.
32
33
KEY-UPDATE for cluster index and type keys should not be permitted -- DELETE/INSERT used instead.
34
NULL may not be used. If there is no data, a SPACE consisting of at least 1 BLANK should be inserted.
35
36
37
Update order for RECORDs in TABLE is as per CLUSTER order within each UOW.
Necessary for exclusion control, and also to prevent DEADLOCK.
Applies to all BATCH/ONLINE DELETE/INSERT/UPDATE operations.
CLUSTER order us updated when updating RECORD after searching with secondary index.
38
39
Sub-queries are not normally allowed. DBA approval is required before using sub-queries.
Created
Updated
2003/5/14
2003/11/20
Page162 / 163
By
FJCL) Ishikawa
By
IBM Shimizu
Phase
External Design
Block name
Document name
Project name
GSPS/A-TOP
C Common
SQL Standards
Function n
Title
Common
SQL Standards
11
Where SQL has been chosen, EXPLAIN must be obtained in the stand-alone test phase to check
the access path.
Based on the results of the EXPLAIN check, the following conditions should be satisfied.
<1> Must be Index SCAN
<2> #Key Columns0
<3> If SORT is generated, ORDER BY conventions (A-TOP standard No.11) must be satisfied
SQL is normally modified in order to change list PREFETCH to either sequential PREFETCH
or None.
<4> Any JOIN other than Nested Loop Join must be approved by DBA
Where PLAN/PACKAGE is bound in the actual environment, the EXPLAIN(YES) option must be
used for BIND processing, to obtain and store access path information.
Where column functions are used, these must be coordinated among individual applications
beforehand and CIT approval must be obtained.
Normally, only restricted column functions such as MIN, MAX and COUNT must be used.
MIN, MAX may only be used in the following cases:
<1> Where MIN, MAX can be limited using Index SCAN
<2> Where DB2 searches 10 records or less in order to determine MIN, MAX
(e.g.: When finding the "latest data validity start time", all KEY items should be specified as
equal sign conditions in the WHERE clause, and there should be no more than 10 records with
"different data validity start times".)
If COUNT is used, convention 1 must be satisfied.
The following standards are normally used for ORDER BY.
<1> Where DB2 internal SORT (determined by Insert Into Sorted Temp Table keywords in Explain)
Created
Updated
Page163 / 163
By
FJCL) Ishikawa
By
IBM Shimizu
used for BIND processing, to obtain and store access path information.
Where column functions are used, these must be coordinated among individual
applications beforehand.
(Note that the number of SORTs is the ANSERSET (searched rows) number, not the FETCH number.
38
2003/5/14
2003/11/20