Você está na página 1de 163

Toyota Motor Asia Pacific Co., Ltd.

Coding Conventions

Fujitsu Systems Business (Thailand) Ltd.


Version :
0.3
Create Date : 15/03/2006
Revise Date : 28/06/2006

On behalf of

On behalf of

TOYOTA Motor Asia Pacific Co.,Ltd.

Fujitsu Systems Business (Thailand) Ltd.

Approved by:

Approved by:

Project Advisor

Mr. Shibutani Kazuhiro

Date
Project Advisor

Mr. Wiriya Tumnao

Date

Project Manager

Ms. Patcharapohn Srirawewongsa

Date
Ms. Chinda Aksornukul

Date
Project Manager

Mr. Yoshiaki Asaka

Date

Date
Project Leader

Project Leader

Prepared By
Date

Mr. Chatchai Sitthichokesiri

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

TMAP Application Standard


TMAP Developer Guide
Function Name
Naming Conventions
Title

Table of Contents

A. Java Coding Convention


A.1. Coding Styles
A.1.1 Comment
A.1.2 Update History
A.1.3 Copyright

A.2. Naming Rules


A.2.1. General
A.2.2. Package
A.2.3. Class
A.2.4. Test Class
A.2.5. Method
A.2.6. Argument
A.2.7. Varibale in General
A.2.8. Local Variable
A.3. Coding Rules
A.3.1. General
A.3.2. Metrics
A.3.3. Format
A.3.4. Comment
A.3.5. Import
A.3.6. Class
A.3.7. Constructor
A.3.8. Method
A.3.9. Class Method
A.3.10. Variable in General
A.3.11. Instance Variable
A.3.12. Class Variable
A.3.13. Local Variable
A.3.14. Inheritance
A.3.15. Instance

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

TMAP Application Standard


TMAP Developer Guide
Function Name
Naming Conventions
Title

A.3.16. Control Structure


A.3.17. Thread
A.3.18. String Manipulation
A.3.19. Number
A.3.20. Date
A.3.21. Collection
A.3.22. Stream
A.3.23. Exception
A.3.24. Garbage Collection
A.3.25. Others
B. Batch Coding Convention
B.1. Coding Styles
B.1.1. Header Section
B.1.2. Include Section
B.1.3. Global Variables Section
B.1.4. Extern Variables Section
B.1.5. Main Function Section

C. SQL Coding Convention


C.1. Coding Styles
C.2. Coding Rules
C.2.1. Rules on Inquiry Processing
C.2.2. Rules on Update Processing
C.2.3. Transaction Rules
D. Shell Script Coding Convention
D.1. Coding Styles
D.1.1. Header Comment

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

TMAP Application Standard


TMAP Developer Guide
Function Name
Naming Conventions
Title

Table of Contents

Created
Updated

2006-03-09
2006-06-14

Page
By
By

5/163
Yusuf
Dani

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

A. Java Coding Convention

Created

2006-03-09

By

Teguh

Updated

2006-06-14

By

Dani

A. Java Coding Convention


A.1. Coding Styles
A.1.1 Comment
The description style about the comment which generates a reference using the javadoc functionality of JDK and which carried out thing consideration,
and the usual comment is specified.
a. Header Comment
A title is attached to a per-file by a header comment.
/************************************************************************************************
*
* Project Name

The version of the source


: TOPS

* Client Name

: TOYOTA

* Program Id

: CommonUtil.java

* Program Name : Common utility Program


* Description
*
* Environment

: This program contains all the Library functions used in


the TopServ Application.
: Java 1.4.2

* 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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

A. Java Coding Convention

8/163

Created

2006-03-09

By

Teguh

Updated

2006-06-14

By

Dani

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Function Name

Coding Conventions

9/163

Page
Title

A. Java Coding Convention

Created

2006-03-09

By

Teguh

Updated

2006-06-14

By

Dani

b. A class / interface comment


It is written before a class and an interface pseudo instruction.
A JavaDoc functionality is taken into consideration.
/**

Notes :

*<pre>

- version is not version set up with tools, such as VAJ.

* Describe an instruction of the functional overview of a class, a disclosure/disclosure,

- When referring to other class (e.g. sms.Test) describe as follow

* a using destination, etc.

@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
*/

c. A method / constructor comment


A function comment is described for every method / constructor.
A JavaDoc functionality is taken into consideration.
/**

Notes :

* Describe the purpose of the class in a brief but complete manner

- '.' (period) is attached to the end of an explanatory text.

* (Ex: Loads a configuration from a standard configuration XML file.)


* @param
:

The argument of a method is described.


However, @param and one argument describe per line.

* @return

An instruction of the return value of a method is described.

* @exception

The exception class to generate is described.

* @throws

Throws SecurityException

*/

Javadoc considers everything up until the period to be an overview

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

10/163

Page

Function Name
Title

A. Java Coding Convention

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 :

* Describe the purpose of the property variable.

- '.' (period) is attached to the end of an explanatory text.

Javadoc considers everything up until the period to be an overview

*/

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.

/*

Writes the contents into a file, and log any exeption

*/
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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

A. Java Coding Convention

Created

2006-03-09

By

Teguh

Updated

2006-06-14

By

Dani

A.1.2. Update History


A modification history is described in the source after changing an existing code.
a. Header comment
Update history is described in the header comment section.
Update history is managed with a version number.
:
* Creation date
* Update history

Refix date

Person in charge

Description

01.00.00

20000418

Toyota)Taro

New creation

01.01.00

20000520

Toyota)Taro

Additional Directory check

01.01.01

20000704

Toyota)Taro

Bug-fix

* XX.XX.XX YYYYMMDD XXXXXXXXX

Make in equal with the version header

:
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

Additional Directory check */

if ( !indir.endsWith(System.getProperty("file.separator")) ) {
setInFileDir( indir + System.getProperty("file.separator") );
}
/* END: 01.01.00

Note (for both single and multi line code modification):


/* START: XX.XX.XX Refix Date Person In Charge Description */
..
/* END: XX.XX.XX Refix Date Person In Charge Description */

20000520

Toyota)Taro

Additional Directory check */

11/163

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.2. Naming Rules


A.2.1. General
N_GNR001 Use English
Explanation /
Motive

Use English for naming.


By this standardization, the code will be more readable by others.
Not Recommended Sample

Recommended Sample

public boolean hasZaiko () {

public boolean hasStock () {

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

variable that only be distinguished by small/capital letter.


By this standardization, the code will be more readable by others
Not Recommended Sample

Recommended Sample

private int number;

private int carNumber;

private int Number;

private int trainNumber

Updated

3/9/2006

By
By

12/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

A. Java Coding Convention

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

N_PKG002 Use name which has mean for package name


Use package name that can be associated with package contents. The meaning of package
Explanation /
Motive

will be difficult to understand if we use function ID or sequential number.


By following this rule, the code will be more readable by others
Not Recommended Sample

th.co.toyota.framework.banking.a00001

Recommended Sample
th.co.toyota.framework.banking.account

N_PKG003 Don't shorten package name


Explanation /
Motive

Use understandable package name, don't shorten it even if it become longer


Not Recommended Sample

th.co.toyota.fw.bkg.acc

Recommended Sample
th.co.toyota.framework.banking.account

N_PKG004 It is possible to have duplication in sub package name


Explanation /
Motive

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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

A. Java Coding Convention

14/163

Created

3/9/2006

By

Teguh

Updated

2006-06-14

By

Dani

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

public class S0001 {

public class Sample {

N_CLS001 Use capital for the first letter of class name


Explanation /
Motive

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

public class sampleclass {

public class SampleClass {

N_CLS002 Put "Exception" at the end of exception class name


Explanation /
Motive

Put "Exception" at the end of exception class name. By this standardization, the code will be more
readable
Not Recommended Sample

Recommended Sample

public class Sample extends Exception {

public class SampleException extends Exception {

N_CLS003 Interface naming follows class naming


Naming rule for interface name basically follow the naming rule of class name.
Explanation /
Motive

By this standardization, the code will be more readable by others


Exception : If the distinction with class name is necessary, put "I" at the head of interface name.
Sample

public class Sample implements ISample {

Updated

3/9/2006

By
By

15/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

By this standardization, the code will be more readable by others


Exception : If there is no suitable name, put "Abstract" at first, then use name which can be
associated with sub class name
Sample

abstract class AbstractSample {


}
N_CLS005 Implementation class naming follows class naming
Naming rule for implementation class name basically follows the naming rule of class name.
Explanation /
Motive

By this standardization, the code will be more readable by others


Exception : If the distinction with interface is necessary, put "Impl" at the end
Sample

public class SampleImpl {


}
N_CLS004 Put "able" at the end for interface that add some ability to class
There are some interface that add some ability to a class such as Runnable, Cloneable, etc.
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

public class Sample implements Pluggable {


}

Updated

3/9/2006

By
By

16/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

17/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

A.2.4. Test Class


N_TCL001 Test Class name should be [test target class name + Test]
Use [test target class name + Test] for test class name.
Explanation /
Motive

By this standardization, the code will be more readable by others.


Sample below consider the use of JUNIT
Sample

public class SampleClassTest extends TestCase {


}
N_TCL002 The name of class which performs all test and package test should be [AllTest] or [package name + Test]
Explanation /
Motive

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

public class AllTest {


}
-----------------------------------------------------package th.co.toyota.banking;
public class BankingTest {
}

Updated

3/9/2006

By
By

18/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

19/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

Do not make the method of the same name as the constructor.


By this standardization, the code will be more readable by others
Not Recommended Sample

Recommended Sample

public class BadSample {

public class FixedSample {

public BadSample() {

public FixedSample() {

public void BadSample (int number) {

public void setNumber (int number) {

N_MTD002 Use capital letter in method name only as a separator


Explanation /
Motive

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

public void Samplemethod () {

public void sampleMethod () {

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

followed by the name of object created by this method


By this standardization, the code will be more readable by others.
Sample

public Sample createSample () {


}
N_MTD004 Use ["to" + object name] for converter method name
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

TMAP Application Standard

TMAP Development Standard

Document Name
Explanation /
Motive

Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

with "to", then followed by the name of object after conversion


Sample

public Another toAnother () {


}
N_MTD005 Use ["get" + attribute name] for getter method name
The name for method which get an attribute (getter method) should start with "get" followed
Explanation /
Motive

by attribute name. By this standardization, the code will be more readable by others.
This is the convention of JavaBeans
Sample

private String sampleName;


public String getSampleName () {
return sampleName;
}
N_MTD006 Use ["set" + attribute name] for setter method name
The name for method which set an attribute (setter method) should start with "set" followed
Explanation /
Motive

by attribute name. By this standardization, the code will be more readable by others.
This is the convention of JavaBeans
Sample

private String sampleName;


public void setSampleName (String name) {
sampleName = name;
}
N_MTD007 Name for method which returns boolean should represent the state of true/false
Use the name by which the state of true/false can be understood for method which returns
Explanation /
Motive

boolean. Use question format which represent Yes or No (Ex : is + Noun)


By this standardization, the code will be more readable by others.
Sample

Updated

3/9/2006

By
By

21/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

public boolean isAsleep () {}


public boolean canSpeak() {}
public boolean hasExpired () {}
public boolean exists () {}
public boolean hasValue () {}
N_MTD008 Consider antonym in english
Consider the symmetrical property of english word for the name of method which its function or
Explanation /
Motive

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

public void send (String message) {}


public String receive () {}

Updated

3/9/2006

By
By

22/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

23/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

private String name;

private String name;

public void setName (String name) {

public void setName (String _name) {

Updated

3/9/2006

By
By

24/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

25/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.2.7. Variable in General


N_VAL001 For boolean variable, makes the state of true/false understood
Use the name by which the state of true/false can be understood for boolean variable.
Use question format which represent Yes or No (Ex : is + Noun)
.By this standardization, the code will be more readable by others.
Explanation /
Motive

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

private boolean isAsleep;


private boolean canSpeak;
private boolean hasExpired;
private boolean exists;
private boolean hasValue;
N_VAL002 Constant should be static final, use capital letter and use "_" as a separator
Constant should be declared as static final, and should use capital letter for variable name. If
Explanation /
Motive

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

public static final int SampleValue = 10;

Recommended Sample
public static final int SAMPLE_VALUE = 10;

Updated

3/9/2006

By
By

26/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

N_VAL003 Use name which reflect the role of variable


Explanation /
Motive

Use name which reflect the role of variable.


By this standardization, the code will be more readable by others
Not Recommended Sample

Recommended Sample

private String str1;

private String serverName;

private String str2;

private String clientName;

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

27/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.2.8. Local Variable


N_LVL001 If the scope is small, local variable name can be shortened
Originally, variable name should reflect the role of the variable. But if the scope is small, short
Explanation /
Motive

name can be used.


"Scope is small" means "contains only few line and does not have nested block"
Not Recommended Sample

Recommended Sample

import java.io.*;

import java.io.*;

public class Sample {

public class Sample {

public static void main (String[] args) {

public static void main (String[] args) {

String str1 = "1 Line";

String index = "1 Line";

try {

try {

String str2 = br.readLine();

BufferedReader br = new BufferedReaded

System.out.println (str1);

(new FileReader ("test.txt"));

System.out.println (str2);

String str = br.readLine();

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

TMAP Application Standard

TMAP Development Standard

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

for (int j = 0; j < 10; j++ ) {

Recommended Sample
for (int i = 0; i < 10; i++ ) {

for (int n = 0; n < 10; n++) {

for (int j = 0; j < 10; j++) {

for (int t = 0; t < 10 < t++) {

for (int k = 0; k < 10 < k++) {

}
}

}
}

Updated

3/9/2006

By
By

29/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

30/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.3. Coding Rules


A.3.1. General
C_GNR000 Use interface for object reference
It is possible to declare using implementation class when refer to an object. However, declare
using interface if an appropriate interface of implementation class exists. The advantage of using
Explanation /
Motive

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.*;

public class BadSample {

public class FixeddSample {

public static void main (String[] args) {

public static void main (String[] args) {

Vector sampleList = new ArrayList();

List sampleList = new ArrayList();

BadSample badSample = new BadSample();

FixedSample fixedSample = new FixedSample();

badSample.badMethod(sampleList);

fixedSample.fixedMethod(sampleList);

public void badMethod (ArrayList input) {

public void fixedMethod (List input) {

}
}

Updated

3/9/2006

By
By

31/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

NC_GNR001 Do not use deprecated API


Explanation /
Motive

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;

public class BadSample {

public class FixeddSample {

public static void main (String[] args) {

public static void main (String[] args) {

Date sampleDate = new Date();

Calendar sampleCalendar = Calendar.getInstance();

System.out.println (sampleDate.getYear());

System.out.println (sampleCalendar.get(
Calendar.YEAR));

C_GNR002 Do not write unused code


Don't you write unused private method / variable, or local variable ? If these exist, code readability
Explanation /
Motive

will decrease, and waste some resources. Delete the one that no longer needed.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class BadSample {

public static void main (String[] args) {

public static void main (String[] args) {

usedMethod ();
}

public void usedMethod () {

public void usedMethod () {

public void unusedMethod () {


}
}

usedMethod ();

Updated

3/9/2006

By
By

32/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_GNR003 Declare with proper modifier


Explanation /
Motive

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

public void internalMethod () {

private void internalMethod () {

C_GNR004 Use "final" properly


Declare final for something that do not change or do not want to change such as class that is
Explanation /
Motive

not inherited, method that is not overridden, or variable that its value does not change (constant).
It will increase code readability.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class FixedSample {

public static int DEFAULT_INTERVAL = 60;


}

public static final int DEFAULT_INTERVAL = 60;


}

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

Default value for primitive type


byte

(byte) 0

short

(short) 0

int

long

0L

float

0.0f

double

0.0d

char

\u0000'

boolean

false

- Data Structure
Explanation /
Motive

Data structure of primitive type and reference type is as follows


Primitive type : has the value itself
Reference type : has the reference of the value
Therefore, there is a difference between these types when substitution is performed
Primitive type : the value itself is substituted
Example
int i = 5;
int j = i;
i and j is different variables with the value 5.
The change of I does not affect j (and vice versa)
Reference type : The reference of a value is substituted
Example
Integer k = new Integer (5)
Integer l = k;
In the example above, l and k point the same value
The change of k will also change l respectively (vice versa)
Image in the memory

Updated

3/9/2006

By
By

34/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions
Stack

Page

Function Name
Title

A. Java Coding Convention


Heap

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

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard

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

C_MTR002 Number of line in a class should be less than 600 lines


Explanation /
Motive

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

C_MTR003 Number of public method in a class should be less than 30.


Explanation /
Motive

Number of public method in a class should be less than 30.


If the number of method exceeds this value, review the design, divide class into multiple classes

C_MTR004 Number of class in a package should be less than 10


Explanation /
Motive

The ideal number of class in a package is 10, at most 20.


If the number of class exceeds this value, review the design, divide package into multiple packages

C_MTR005 Do not make circulative complexity bigger.


The code will be more complex if number of nested block, class/method invocation is great. If the
Explanation /
Motive

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

TMAP Application Standard

TMAP Development Standard

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

public class FixedSample {

Recommended Sample
public class FixedSample {

private int bottom = 5;

private int bottom = 5;

private int height = 10;

private int height = 10;

private int constant = 2;

private int constant = 2;

public int getArea() {

public int getArea() {

int area = (bottom * height) / constant;

int area = (bottom * height) / constant;

return area

return area

C_FMT002 Use 4 characters of blank space for indent


Explanation /
Motive

Unless there is a specific agreement, use 4 character for indent.


By this standardization, the code will be more readable by others
Not Recommended Sample

public class FixedSample {

Recommended Sample
public class FixedSample {

private int bottom = 5;

private int bottom = 5;

private int height = 10;

private int height = 10;

private int constant = 2;

private int constant = 2;

public int getArea() {

public int getArea() {

int area = (bottom * height) / constant;

int area = (bottom * height) / constant;

return area

return area
}

Updated

3/9/2006

By
By

38/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Function Name

Coding Conventions

Page
Title

Created
A. Java Coding Convention

C_FMT003 Avoid too long line


Limit the number of character in one line to 80 characters. It becomes hard to see in monitor,
causes some difficulties in printing and email sending, and causes the format collapses.
Here is the place to start new line
Explanation /
Motive

1. Start new line after comma


2. Start new line before operator which has low priority
3. Divide process into several line by substituting variable etc
Put the starting point of new line in position like Recommended Sample 2.
Sample

[Not Recommended Sample]


public void longLineMethod( boolean booleanValue, String stringValue, int intValue){
}
[Recommended Sample]
1. Start new line after comma
public void fixedMethod( boolean booleanValue,
String stringValue,
int intValue){
}
2. Start new line before operator
double length = Math.sqrt(Math.random()
+ Math.pow(Math.random(), 2.0));
3. Substitute variable
double xSquared = Math.pow(Math.random(), 2.0);
double length = Math.sqrt(Math.random() + xSquared);

Updated

3/9/2006

By
By

39/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_FMT004 Do not write any statement after "{"


Explanation /
Motive

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

private void badSampleMethod () { int i = 0;

Recommended Sample
private void fixedSampleMethod () {

int i = 0;
}

C_FMT005 Write only one statement in one line


Explanation /
Motive

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

public int badSampleMethod (int top, int bottom) {

Recommended Sample
public int fixedSampleMethod (int top, int bottom) {

int result = top - bottom; return result;

int result = top - bottom;


return result;

C_FMT006 Put blank space after comma


Explanation /
Motive

Put blank space after comma. It will improve code readability


Not Recommended Sample

Recommended Sample

public void badSampleMethod(int score,int number){

public void fixedSampleMethod(int score, int number){

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_FMT008 Put blank space after semicolon in FOR statement


Explanation /
Motive

Put blank space after semicolon in FOR statement. It will improve code readability
Not Recommended Sample

Recommended Sample

for (int i = 0;i < 1000;i++){

for (int i = 0; i < 1000; i++){

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

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard

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

Not Recommended Sample

Recommended Sample

if (a+ b){

if (a + b){

if (a %b){

if (a %b ){

if (a/b){

if (a / b){

C_FMT013 Do not use parenthesis in return statement


Do not use unnecessary parenthesis in return statement. In the java specification, return object
is only one. It will confuse return statement with method if you use a parenthesis in return

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);

return (int) a;

C_FMT014 boolean variable is already compared


Don't you compare boolean variable with true ? Boolean variable does not need to be compared
Explanation /
Motive

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_FMT015 Inequality sign should be left-pointing


By standardization of inequality sign direction, code readability will improve. Except there is any
special purpose, the direction should be left pointing.
Exception :

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 ){

}else if( a > i){

}else if( i < a ){

Updated

3/9/2006

By
By

44/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_CMT002 As for the comment, write only necessary one concisely


It becomes difficult to corect if we write comment more than the necessity. Therefore we write
"As for comment, write only necessary one concisely". The following is the trick for writing
readable comment.
1. Declare variables with undestandable / meaningful name, so we can save trouble for
Explanation /
Motive

explaining those with comment


2. Do not write updated person and updated date
3. If the comment is unavoidably becomes long, write the summary in one line.
It is not necessary to explain every logic like the following sample.
Comment is necessary if the logic is complex. Complex logic has multipe points, therefore by dividing
it into several methods and adding comment as method's javadoc, we can make a better code
Not Recommended Sample

public class BadCommentSample {

Recommended Sample
public class FixedCommentSample {

/**

/**

* Method to find the sum

* Method to find the sum

* @param elements Array of int to find the sum

* @param elements Array of int to find the sum

* @return Sum of array

* @return Sum of array

*/

*/

public int sum(int[] elements){

public int sum(int[] elements){

// Variable to store the sum

int sum = 0;

int sum = 0;

for(int i = 0; i < elements.length; i ++){

//Loop to calculate the sum of array

sum += elements[i];

for(int i = 0; i < elements.length; i ++){

// Take out one element, calculate the sum


sum += elements[i];
}
// Return the result
return sum;
}

return sum;
}

Updated

3/9/2006

By
By

47/163
Teguh

Phase

Project Name

Block Name
Document Name
}

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

48/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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 {

public class FixedSample{

Updated

3/9/2006

By
By

49/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

so the code is optimized more appropriately


2. Code readability will improve, because it is
Not Recommended Sample

Recommended Sample

public class BadSample {

public final class FixedSample {

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

public class BadSample {

Recommended Sample
public class FixeddSample {

int rank;

public int number;

private int age;

int rank;

public int number;


}

private int age;


}

Updated

3/9/2006

By
By

50/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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 () {

C_CRT002 In principle, create default constructor


By specifying the default constructor, it becomes possible to do the following
Explanation /
Motive

Create instance dynamically by using Class.newInstance()


Set the default value of instance variable, and when instance is generated it will be initialized
by that value.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class FixedSample {

private int number;

private int number;

public BadSample(int num){

public FixedSample(){

number = num;

this(10);

public FixedSample(int num){


number = num;
}
}

Updated

3/9/2006

By
By

51/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

C_MTD002 Use array which it's size is 0


Isn't there a possibility that null is returned by the method which returns array? If null is returned,
Explanation /
Motive

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;

public class BadSample{

public class FixedSample{

public String[] getStringList(List slist){

public String[] getStringList(List slist){

if (slist.size() == 0){

String[] result = (String[])slist.toArray (

return null;

new String[slist.size()]);

} else{

return result;

String[] result = (String[])slist.toArray (


new String[slist.size()]);
return result;
}
}
}

}
}

Updated

3/9/2006

By
By

52/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

After correction, stockRightSpeaker and stockLeft

Speaker values as attributes. If speaker is always

Speaker is not accessed separately. Both values are

sold in a set of right/left speaker, there is a design

changed using one method. The assumption that

problem in code below.

speaker is sold in pair can be kept.

public class BadSample {

public class BadSample {

private int stockRightSpeaker;

private int stockRightSpeaker;

private int stockLeftSpeaker;

private int stockLeftSpeaker;

public void buyRightSpeaker(int quantityRight) {

public void buyRightSpeaker(int quantity) {

stockRightSpeaker =

stockRightSpeaker =

stockRightSpeaker-quantityRight;

stockRightSpeaker-quantity;

stockLeftSpeaker =

public void buyLefttSpeaker(int quantityLeft) {

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_MTD004 A method should only have one role


Aren't multiple process performed in a method? If different type of multiple process is performed in
Explanation /
Motive

a method, It will affect code readability, maintainability, extensibility and reusability.


Divide method based on its function.
Not Recommended Sample

Recommended Sample

import java.awt.Point;
public class BadSample {

public class FixedSample {

public static void main(String[] args){

public static void main(String[] args){

Point point = new Point(55, 77);

Point point = new Point(55, 77);

BadSample smpl = new BadSample();

FixedSample smpl = new FixedSample();

smpl.switchXandY(point);

smpl.printValue(point);

smpl.switchXandY(point);

// Swap and display the value

smpl.printValue(point);

private void switchXandY(Point point){

StringBuffer sb =new StringBuffer();

// Swap the value

sb.append("X is ");

private void switchXandY(Point point){

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();

private void printValue(Point point){

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

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

sb.append(point.getY());
System.out.println(sb);
}
}

C_MTD005 Do not use "this" as return value of method


Please reconsider why we should use "this" as a return value of method. Is there any specific
Explanation /
Motive

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

Sample sample = new Sample();


sample.sampleMethod1();
sample.sampleMethod2();
sample.sampleMethod3();

2.

sample.sampleMethod1().sampleMethod2().sampleMethod3();

But avoid it because it can cause code readability problem


C_MTD006 Do not overload method which has the same number of argument
In method' overload, if the number of arguments are the same, it not easy to understand which
Explanation /
Motive

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

TMAP Application Standard

TMAP Development Standard

Document Name

Function Name

Coding Conventions

public String classify(Object sampleObject){


return "Unknown Object";
}
public String classify(String sampleString){
return "String";
}
public String classify(Exception sampleException){
return "Exception";
}
public static void main(String args[]){
BadSample badSample = new BadSample();
Object sample1 = new Object(); // 1
String sample2 = new String(); //2
Exception sample3 = new Exception(); // 3
System.out.println(badSample.classify(sample1)); // 1'
System.out.println(badSample.classify(sample2)); // 2'
System.out.println(badSample.classify(sample3)); // 3'
}
}
The result is
Unknown Object
String
Exception
We do not know which method is executed by only seeing line 1' 2' and 3'.
Therefore we need to see line 1, 2, and 3 to check the instance type.

Page
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

56/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.3.9. Class Method


C_CMD001 Use class name when invoke class method
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public static void sampleClassMethod(){}

public static void sampleClassMethod(){}

public void sampleMethod(){

public void sampleMethod(){

BadSample object = new BadSample();

FixedSample object = new FixedSample();

object.sampleClassMethod();

FixedSample.sampleClassMethod();

}
}

}
}

Updated

3/9/2006

By
By

57/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

A.3.10. Variable in General


C_VAL001 Declare only one variable in a statement
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

private String firstName, lastName;

private String firstName;

private String lastName;


}

C_VAL002 Do not use literal


Isn't there location where literal is used? Literal is expression that appears directly in the code as
a constant, and indicates the one that it is not possible to express it by the symbol and the list
Explanation /
Motive

(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

public class BadSample {

Recommended Sample
public class FixedSample {

private int[] sampleArray = new int [10];

private static final int ARRAY_SIZE = 10;

private int[] sampleArray = new int [ARRAY_SIZE];


}

Updated

3/9/2006

By
By

58/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_VAL003 Declare array as "variable type[]"


Please standardize the array declaration form in the code to keep the consistency of the code.
Explanation /
Motive

The declaration form like the following "Not Recommended Sample" seems to remain as
an influences of C language.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class FixedSample {

private int sampleArray[] = new int[10];


}

private int[] sampleArray = new int[10];


}

C_VAL004 Use local variable as far as possible


When variable is accessed frequently, is the performance taken into consideration?
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

private int result;

private int result;

public void addNumber(int[] numbers) {

public void addNumber(int[] numbers) {

for (int i = 0; i < numbers.length; i++){

int tempSum = result;

result += numbers[i];

for (int i = 0; i < numbers.length; i++) {

tempSum += numbers[i];

}
result = tempSum;
}

Updated

3/9/2006

By
By

59/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_VAL005 Declare "final" for constant


The value that doesn't change through the entire class is a constant.
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

private int constant = 5;

private final int CONSTANT = 5;

private int getSize(int number) {

private int getSize(int number) {

return number * constant;

return number * CONSTANT;

C_VAL006 Use local variable and instance variable properly


Is instance variable used when local variable is sufficient ? Declaring unnecessary instance
Explanation /
Motive

variable will cause performance and code readability decrease and multithread become inconsistent.
Use instance variable after considering its necessity.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class FixedSample {

// Variable which is only used in a method


private int value;
// value is only use in this method
public void calcValue(SomeObj inValue){

public void calcValue(SomeObj inValue){

value = inValue.getData();

int value = inValue.getData();

for(int i = 0; i < value; i++){

for(int i = 0; i < value; i++){

//process

//process

}
}

}
}

Updated

3/9/2006

By
By

60/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

61/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

Updated

A.3.11. Instance Variable


C_IVL001Initialize instance variable in constructor, or when declaring instance variable, or in first time getter method is accessed (Lazy initialization)
There are three methods of initializing instance variable , in constructor, or in instance variable
declaration, or in first time getter method is accessed.
Each method's advantages and disadvantages are written below.
[Constructor]
Advantages
1. Thread safe
2. It is possible to initialize different value for each instance
Disadvantage
1. There is a possibility of forgetting initialization, because variable declaration and initialization
are performed in separated location.
[Instance Variable Declaration]
Advantages
1. Thread safe
Explanation /
Motive

2. Instance generation is fast


Disadvantage
1. Initialization can not be performed for each instance
[First time getter method is accessed]
Advantages
1. Initialization operation can be overridden in by overriding getter method in sub class.
2. It is not necessary to perform null checking in a place where get method is called.
( Because null checking is performed inside get method).
3. Implementation of delaying variable initialization with instance generation can be achieved.
Disadvantages
1. Inconsistency will occur if get method is called from multiple threads at the same time
2. It takes greater load because each time getter method is called, the check whether variable

3/9/2006

By
By

62/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

if (name == null) {
name = "suzuki";
}
return name;
}
}

C_IVL002 Declare instance variable as private


Is instance variable declared as public or default (package.private) and manipulated directly?
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public int value = 10;

private int value = 10;

public int getValue() {


return value;

public class BadSampleMain {


public static void main( String[] args) {

}
}

BadSample sample = new BadSample();


sample.value += 10;

public class FixedSampleMain {

System.out.println(sample.value);

public static void main( String[] args) {

FixedSample sample = new FixedSample();

int result = sample.getValue();


result += 10;
System.out.println(result);
}
}

Updated

3/9/2006

By
By

64/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

65/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.3.12. Class Variable


C_CVL001 Do not use array which is declared as "public static final"
Don't you think that the element of array which is declared as final is not modifiable? When
Explanation /
Motive

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

public class BadSample {

Recommended Sample
import java.util.*;

public static final int[] SAMPLE_ARRAY= {0, 1, 2, 3};


public static void main(String[] args){

public class FixedSample {

SAMPLE_ARRAY[0] = 1; \\ can be modified

private static final int[] SAMPLE_ARRAY

= {0, 1, 2, 3};

public static final List IMMUTABLE_ARRAY =


Collections.unmodifiableList(
Arrays.asList(sampleArray));
}

C_CVL002 Use class name to access class variable


Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public static final int STATIC_VALUE = 10;

public static final int STATIC_VALUE = 10;

public void sampleMethod(){

public void sampleMethod(){

BadSample object = new BadSample();

FixedSample object = new FixedSample();

int localValue =object.STATIC_VALUE;

int localValue =FixedSample.STATIC_VALUE;

}
}

}
}

Updated

3/9/2006

By
By

66/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

67/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.3.13. Local Variable


C_LVL001 Declare local variable right before you use it
Limit the scope of local variable. Don't you declare all local variables at the beginning of the code ?
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public static void main(String[] args){

public static void main(String[] args){

int localValue1 = 10;

TestClass test = new TestClass();

int localValue2 = 20;


int localValue3 = 30;

int localValue1 = 10;


test.sampleMethod1(localValue1);

TestClass test = new TestClass();

..
int localValue2 = 20;

test.sampleMethod1(localValue1);

test.sampleMethod2(localValue2);

..

..

test.sampleMethod2(localValue2);

int localValue3 = 30;

..

test.sampleMethod3(localValue3);

test.sampleMethod3(localValue3);

..

..
}
}

}
}

Updated

3/9/2006

By
By

68/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_LVL002 DO not reuse local variable easily


Don't you reuse once declared local variable for multiple purpose easily? Declare and initialize
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public void method(int a) {

public void method(int a) {

int i;

for (int i = 0; i < a; i++) {

for (i = 0; i < a; i++) {

for (int i = 0; i < a; i++) {

for (i = 0; i < a; i++) {

int total = a * 2

i=a*2
}
}

}
}

Updated

3/9/2006

By
By

69/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

70/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Created

Title

A. Java Coding Convention

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

public class BadSample{

Recommended Sample
public class FixedSample{

protected int number = 4;

protected int number = 4;

public class ChildBadSample extendsBadSample{

public class ChildFixedSample extendsFixedSample{

protected int number = 5;

protected int childNumber = 5;

public static void main(String[] args){

public static void main(String[] args){

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);
}

The execution result of above program is the following

number is 5
super.number is 4

The execution result of above program is the following


number is 4
super.number is 4
childNumber is 5

Updated

3/9/2006

By
By

71/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

C_IHT002 Use abstract method


Isn't there empty method that not processing anything? Declare as abstract for a method which
Explanation /
Motive

has not been implemented yet.


The implementation leakage in subclass can be prevented by doing so.
Not Recommended Sample

Recommended Sample

public abstract class BadSampleimplements ISample {

public abstract class FixedSampleimplements ISample {

public void sampleMethod() {}

public abstract void sampleMethod() {}

public interface ISample {

public interface ISample {

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

Example of non-private method of super class overidden by method in subclass


// Super Class
public class Parent {
public void sampleMethod(){
System.out.println("Parent: method");
}
public static void main(String[] args){
Child childInstance = new Child ();
test(childInstance);
}
public static void test(Parent parentInstance){

// Super class type argument

Updated

3/9/2006

By
By

72/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard

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;

// return true if id value is equals

}
}
}
}
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

TMAP Application Standard

TMAP Development Standard

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

Object.toString() method returns the value obtained by hashCode(). It is necessary to override


toString() method to get more easy-to-understand value.
Not Recommended Sample

public class BadSample{

Recommended Sample
public class FixedSample{

private int sampleValue;

private int sampleValue;

public BadSample(int value){

public FixedSample(int value){

sampleValue = value;
}
public static void main(String[] args){
System.out.println(
}

sampleValue = value;
}

new BadSample(100));

public String toString(){


StringBuffer result =
new StringBuffer("FixedSample[");

Updated

3/9/2006

By
By

75/163
Teguh

Phase

Project Name

Block Name
Document Name

TMAP Application Standard

TMAP Development Standard

Page

Function Name

Coding Conventions

Title

result.append(sampleValue);

If we execute above program, we get the following

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

TMAP Application Standard

TMAP Development Standard

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

public class BadSample {

Recommended Sample
public class FixedSample {

public static void compare( String left, String right){

public static void compare( String left, String right){

if( left == right ){

if( left.equals(right) ){

System.out.println( "They are equal.");

System.out.println( "They are equal.");

} else {

} else {

System.out.println( "They are NOT equal.");

System.out.println( "They are NOT equal.");

}
}

}
}

Updated

3/9/2006

By
By

77/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_IST002 Do not compare class object by using class name


Isn't class is compared by the name (Name acquired by getName() method in Class class ) ?
Explanation /
Motive

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.*;

public class BadSample{

public class FixedSample{

private List sampleList = new ArrayList();

private List sampleList = new ArrayList();

public boolean hasSameList(List list){

public boolean hasSameList(List list){

Class classA = sampleList.getClass();

ClassclassA =sampleList.getClass();

Class classB = list.getClass();

Class classB = list.getClass();

String classAName = classA.getName();

return classA.equals(classB);

String classBName = classB.getName();

}
}

return classAName.equals(classBName);
}
}

Updated

3/9/2006

By
By

78/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.3.16. Control Flow


C_CTR001 Do not omit "{}" in control statement (if, else, where, for, do, while)
Isn't "{}" of control statement omitted? Even if the process contains only one line, do not omit "{}"
Explanation /
Motive

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

public class BadSample{

public class FixedSample{

public void badSampleMethod( boolean flag){

public void fixedSampleMethod( boolean flag){

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

Please consider the following points for unfinished code


- Describe proper process
- Comment out collectively
Not Recommended Sample

for(int i = 0; i < 10; i++ ){


// will be implemented later.
}

Updated

3/9/2006

By
By

79/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Created

Title

A. Java Coding Convention

C_CTR003 Do not use "=" in conditional expression of if/while


The case of using substitution operator ("=") in the condition of if or while is hardly thought,
excluding the case of to substitute the return value of the method.
Explanation /
Motive

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

public class BadSample{

Recommended Sample
public class FixedSample{

public String badSampleMethod( boolean flag){

public String fixedSampleMethod( boolean flag){

String value = 0;

String value = 0;

if (flag = true) {

if (flag == true) {

value = a;

//should be written if (flag)

value = a;

return value;

return value;

In example above, true is substituted to flag, therefore


condition result is always true.
C_CTR004 Use if and while properly
Do you use for and while aware their differences? Use for statement for processing array, or if
the number of loop is clear. Mis-use of those statements will decrease code readability.
Explanation /
Motive

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

Do not omit increment in for statement

Use for statement for loop process which incrementing

public class BadSample{

counter.

void method(int x){


// Do not omit counter and increment

public class FixedSample{


void method(String[] arrayStr){

Updated

3/9/2006

By
By

80/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

int i = 0;

int size = arrayStr.length;

for (; i < x; ) {

for(int i = 0; i < size; i++){

i++;

Created
A. Java Coding Convention

System.out.println(arrayStr[i]);

}
}

If there is no special reason, use for statement for


incrementing number.

When increment is not necessary, use while statement.

public class AnotherBadSample{

import java.util.StringTokenizer;

void method(int x){

public class WhileLoopSample{

int i = 0;

void sampleMethod(String target){

while (i < x) { // For statement is suitable

StringTokenizer strToken =

i++;

new StringTokenizer(target);

while(strToken.hasMoreTokens()){

System.out.println( strToken.nextToken());

}
}

Use while statement like "Recommended Sample"


if increment is not necessary.
void sampleMethod(String target){
StringTokenizer strToken =
StringTokenizer(target);
for(int i=0;strToken.hasMoreTokens();i++){
System.out.println( strToken.nextToken());
}
}

Updated

3/9/2006

By
By

81/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Function Name

Coding Conventions

C_CTR005

Page
Title

Created
A. Java Coding Convention

Do not change the value of loop variable in for statement.


Isn't the counter of for statement changed in the loop? The counter of for statement should not be

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

public class BadSample{

Recommended Sample
public class FixedSample{

int badSampleMethod(){

int fixedSampleMethod(){

int result = 0;

int result = 0;

for (int i = 0; i < 100; i++){

for (int i = 0; i < 50; i++){

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

public class BadSample{

Recommended Sample
public class FixedSample {

public static void main(String[] args){

public static void main(String[] args){

int[] testArray = new int[10];

int[] testArray = new int[10];

for (int i = 1; i <= 10; i++){

for (int i = 1; i <= 10; i++){

testArray[i-1] = i;

testArray[i-1] = i;

}
}

}
}

Updated

3/9/2006

By
By

82/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_CTR006 Avoid using break or continue


if break and continue are used to control processing in the loop, control structure will get complex
and code readability will drop. Mostly of such logic can be written without using break or continue

Explanation /
Motive

Please use neither break nor continue as much as possible to simplify control structure and
improve code readability.
Not Recommended Sample

public class BadSample{

Recommended Sample
public class FixedSample{

public static void main(String[] args){

public static void main(String[] args) {

BadSample sample = new BadSample();

FixedSample sample = new FixedSample();

sample.useContinue();

sample.unUseContinue();

sample.useBreak();

sample.unUseBreak();

private void useContinue(){

private void unUseContinue(){

int skipNumber = 5;

int skipNumber = 5;

for (int i = 0; i < 10; i++){

for (int i = 0; i < 10; i++){

if ((i + 1) == skipNumber){

if ((i + 1) != skipNumber){

continue;

System.out.println(i + 1) ;

System.out.println(i + 1);

}
private void useBreak(){

private void unUseBreak(){

int limitNumber = 5;

int limitNumber = 5;

for (int i = 0; i < 10; i++){

for (int i = 0; (i + 1) <= limitNumber;i++){

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

}
Execution Result

Execution Result

10

10

C_CTR008 Use System.arraycopy() method to copy array


Isn't loop is used to copy array? System.arraycopy() is a method for copying array. Writing of
Explanation /
Motive

copying process by ourselves will be a waste, prone to error and decrease the execution speed.
Use System.arraycopy instead.
Not Recommended Sample

public class BadSample{


String[] copy(String[] orgArray){
if(orgArray == null){

Recommended Sample
public class FixedSample{
String[] copy(String[] orgArray){
if(orgArray == null){

return null;

return null;

int length = orgArray.length;

int length = orgArray.length;

Updated

3/9/2006

By
By

84/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

String[] copyArray = new String[length];

String[] copyArray =new String[length];

for (int i = 0; i < length; i++){

System.arraycopy(orgArray, 0,

copyArray[i] = orgArray[i];

copyArray, 0, length);

return copyArray;

return copyArray;

C_CTR009 Minimalize the generation of object in repetitive process


The generation of object within loop which its repeat count is large can cause the performance
Explanation /
Motive

drop, because much time is required to generate object. To avoid this problem, create instance
outside loop, and reuse it.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class FixedSample {

public void badSampleMethod( String[] array){

public void fixedSampleMethod( String[] array){

for (int i = 0; i < array.length; i++) {

StringBuffer sampleBuffer =

StringBuffer sampleBuffer =

new StringBuffer();

new StringBuffer();

for (int i = 0; i < array.length; i++) {

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

TMAP Application Standard

TMAP Development Standard

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

Below is a sample in which polymorphism is not used

Below is a sample in which polymorphism is used

public class BadSample{

public class FixedSample{

public static void main(String[] args) {

public static void main(String[] args) {

Object[]animals = new Object[2];

Animal[]animals = new Animal[2];

animals [0] = new Dog();

animals [0] = new Dog();

animals [1] = new Cat();

animals [1] = new Cat();

int size = animals.length;

int size = animals.length;

for (int i = 0; i < size; i++){

for (int i = 0; i < size; i++){

if(animals[i] instanceof Dog){

animals[i].cry();

((Dog)animals[i]).bark();

}else if(animals[i] instanceof Cat){


((Cat)animals[i]).meow();
}

}
}
public abstract class Animal{

}
}

abstract void cry();


}

}
public class Dog {

public class Dog extends animal{

public void bark(){

public void bark(){

System.out.println("Woof woof");

System.out.println("Woof woof");

public class Cat extends Animal {

public class Cat extends Animal {

public void meow(){

public void meow(){

System.out.println("Meow meow");
}

System.out.println("Meow meow");
}

Updated

3/9/2006

By
By

86/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_CTR011 Do not use try block in repetitive process.


Do not put try/catch block in the loop. It will lead to the decrease of performance, and process in
the loop will be difficult to see. Do try/catch outside loop, except for any special reason.

Explanation /
Motive

[Exception]
If we want to execute process until the end of the loop even if exception is occurred.
Not Recommended Sample

public class BadSample{

Recommended Sample
public class FixedSample{

public void method(String[] str){

public void method(String[] str){

int size = str.length;

int size = str.length;

for(int i = 0; i < size; i++){

try {

try {

for(int i = 0; i < size; i++){


int num = Integer.parseInt(str[i]);

int num = Integer.parseInt(str[i]);

someOtherMethod(num);

someOtherMethod(num);

catch(NumberFormatException e) {

catch(NumberFormatException e) {

e.printStackTrace();

e.printStackTrace();

private void someOtherMethod(int i){

private void someOtherMethod(int i){

}
}

}
}

Updated

3/9/2006

By
By

87/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

88/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

// Class below is subclass of Thread

// Class below is subclass of Controller class which

public class BadSampleControllerextends Thread{

has thread function

private Car car;

public class FixedSampleController extends Controller

public BadSampleController (Car _car){

implements Runnable{

car = _car;

private Car car;

public FixedSampleController (Car _car){

public void run(){

car = _car;

car.startEngine();

//

public void run(){

car.startEngine();

//
}
}

Updated

3/9/2006

By
By

89/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_TRD002 Use notifyAll() method to resume waiting thread


Use notityAll() method instead of notify() method to resume waiting thread. When the wait()
method is called for certain object, present thread will stop and enter waitset. To resume thread
from waitset, we can call notify() method or notifyAll() method.
If multiple threads in an object are in waiting state, we can resume one of those threads by using
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public void refuel(int _fuel){

public void refuel(int _fuel){

synchronized(car){

synchronized(car){

fuel = _fuel;

fuel = _fuel;

car.notify();

car.notify();

} // ...

} // ...

C_TRD003 Do not use yield() method of Thread class


Because the control method of Thread.yield() method is different according to Java VM, how the
application run is not assured. Thread.yield() method is just a method to speed up thread switching.
After discarding the control of Thread A, it can not be assured to which thread the control moves
Explanation /
Motive

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

public class ThreadBadSample {

Title

Created
A. Java Coding Convention

public class ThreadFixedSample {

private LockObject lock;

private LockObject lock;

public void longProcess(){

public void longProcess(){

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

3. The lock order of object is undecided.


The process of calling a method which has synchronized block from synchronized block means
go to lock another object while having another lock object without releasing it. It has already met
1 and 2 conditions. In addition of these, if lock order of object is undecided, deadlock can easily
occur. If the order of lock resources is not strictly set, do not call a method which has
synchronized block from synchronized block.
Explanation

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

TMAP Application Standard

TMAP Development Standard

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.

C_TRD006 Use wait(), notify(), notifyAll() from synchronized block


wait() method, notify() method, notifyAll() method can not be called if thread is not in a state of
Explanation /
Motive

holding lock of object. Java.lang.IllegalMonitorStateException will be thrown if they are called


without having the lock of object.
Not Recommended Sample

public class BadSample{


public static void main(String[] args){

Recommended Sample
public class FixedSample{
public static void main(String[] args){

Test test = new Test();

Test test = new Test();

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

}
}
}

If program above is executed, the following exception

Sample above do not throw an exception

will be thrown. The result will be the same in case


notify() or notifyAll() is called
Exception in thread "main"
java.lang.IllegalMonitorStateException:
current thread not owner
C_TRD007 Use wait() method from while block.
Use wait() method in while loop. In many cases, wait() is called when we want thread to wait
Explanation /
Motive

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){

while (fuel == null){

try{

try{
car.wait();

car.wait();

}catch(InterruptedException e){

}catch(InterruptedException e){

e.printStackTrace();

e.printStackTrace();

car.drive();

car.drive();

It is not possible to move in the Car object (car) if there

To correct sample in left column, we simply change

is no fuel. Therefore when the fuel field is null, thread

if to while.

is set to wait(). This process seems run normally.

in if statement, after process inside statement is

However, how if following things happen?

executed once, it moves to the next operation. In while

Updated

3/9/2006

By
By

93/163
Teguh

Phase

Project Name

Block Name
Document Name

TMAP Application Standard

TMAP Development Standard

Function Name

Coding Conventions

1. notifyAll() is called by intention or by mistake, thread


resume even though fuel is still null.
2. notifyAll() is called in a location which is not related
to this process, and thread resume.
3. Fuel is refilled and notifyAll() is called, but another
thread take the lock of car and change the fuel state.
If above things happen, it can not be assured that
car.drive() will be normally called when fuel is not null.

Page
Created

Title

A. Java Coding Convention

statement, after process inside the statement is


executed, it evaluates the condition again. If evaluation
result is true, then process inside while statement
will be executed. If evaluation result is false, it will
escape from while statement and moves to the next
operation.
if (<condition>) {

while (<condition>) {
//process

//process
}

Therefore, when thread is resumes even if fuel is null,


the condition will be re-evaluated, if fuel is null wait()
method will be called again. It can be assured that
when car.drive() is called, fuel is not null.

C_TRD008 Use wait() , notifyAll() instead of polling loop for queuing


Use wait() and notifyAll() method for waiting process, because polling loop may cause the
performance decrease. Polling loop is a loop which inquire itself whether the condition is satisfied,
and the process is only performed when the condition is satisfied ( the opposite is, after
that the condition is satisfied notified by other party, the next process will be executed)
A lot of processor cycles are consumed when inquiry is done frequently by the polling loop.
Explanation /
Motive

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

public class Robot implements Runnable{

Title

A. Java Coding Convention

public class Robot implements Runnable{

private static byte[] commands;

private static byte[] commands;

private RobotController controller;

private RobotController controller;

public void run(){

public void run(){

synchronized(controller){

synchronized(controller){

while (commands == null){

while (commands == null){

try{

try{
Thread.sleep(10000);

controller.wait();

}catch(InterruptedException e){

}catch(InterruptedException e){

e.printStackTrace();

e.printStackTrace();

int size = commands.length;

int size = commands.length;

for(int i = 0; i < size; i++){

for(int i = 0; i < size; i++){

this.processCommand(commands[i]);

this.processCommand(commands[i]);

commands = null;

commands = null;

public void storeCommands(byte[] commands){

public void storeCommands(byte[] commands){

this.commands = commands;

this.commands = commands;

private void processCommand(byte command){

private void processCommand(byte command){

//

//

}
}

Created

}
}

Updated

3/9/2006

By
By

95/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

public class RobotController{

public class RobotController{

In while statement, if process below is executed, the

In this sample, sleep() is modified to wait(). If the con

condition to move to the next process can be satisfied.

dition of while statement is not satisfied, wait() will be

Robot.storeCommands(commands);
However, until this process is performed, every 10000

executed. If notifyAll() is called after condition is


satisfied, waiting controller will be resumed.

ms (10 s) the condition in while statement will be

Robot.storeCommands(commands);

evaluated and sleep() each time. Even if the condition

controller.notifyAll();

is satisfied, it can not move to the next process until


sleep() is over.

C_TRD009 Apply synchronization (synchronized) only in necessary part


There are two methods to perform synchronization, the first is to declare synchronized method,
and the second is to use synchronized block.
[1. Synchronized method]
synchronized void method() {

[2. Synchronized block]


void method() {

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

TMAP Application Standard

TMAP Development Standard

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 {

private String name;

private String name;

private long birthday;

private long birthday;

public synchronized void setName(Stringname){

public void setName(String name){

this.name = name;

synchronized(this.name){

this.name = name;

public synchronized void setBirthDay(longday){

birthday = day;

public void setBirthDay(long day){

synchronized(birthday){

When setName() is executed, setBirthDay can not be

birthday = day;

called

}
}
}

Updated

3/9/2006

By
By

97/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

98/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.3.18. String Manipulation


C_STR001 Use equals() method to compare strings
Do you use "==" or "!=" operator for comparing strings? If those operators are used, it does not
compare if strings are the same character string or not, but compare if strings are the same
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class BadSample {

public boolean compare(String name,

public boolean compare(String name,

String anotherName){

String anotherName){

return name == anotherName;

return name.equals(anotherName);

C_STR002 Do not use new for literal


Is new used when creating String object to store string constant? If new is used, depends on
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

private String sampleString =new String (Literal);

private String sampleString = Literal;

public void print() {

public void print() {

System.out.println(sampleString);

System.out.println(sampleString);

}
}

}
}

Updated

3/9/2006

By
By

99/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_STR003 Use StringBuffer class for modifiable string


Do you concatenate character string defined as String which cannot be changed (fixed character
string) using operator "+" ? String object is fixed character string. Every time we concatenate string
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public String getFruitName() {

public String getFruitName() {

String fruit = apples;

StringBuffer fruit = new StringBuffer(15);

fruit += , bananas;

fruit.append(apples);

return fruit;

fruit.append(, bananas);

return fruit.toString();

}
}

C_STR004 Use String class for fixed character string


Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public void displayMessage() {

public void displayMessage() {

StringBuffer buffer

String output = Message;

= new StringBuffer(Message);

System.out.println(output);

String output = buffer.toString();


System.out.println(output);
}
}

}
}

Updated

3/9/2006

By
By

100/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

public class BadSample {

Recommended Sample
public class FixedSample {

public boolean validate( String userInput) {

public boolean validate(String userInput) {

return (userInput != null

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

Convet int to String

Convet int to String

String sample = + integer;

String sample = String.valueOf(integer);

String sample =(new Integer(integer)).toString();


Convert String to int
Convert String to int
int integer =(new Integer(sample)).intValue();
int integer =Integer.valueOf(sample).intValue();

int integer = Integer.parseInt(sample);

Updated

3/9/2006

By
By

101/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_STR007 Use charAt() method to look up certain character in the string.


Use charAt() method to look up certain character in the string if the argument is one character.
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public boolean checkHead( String checkString) {

public boolean checkHead( String checkString) {

return (checkString.startsWith(E);

return (checkString.length() > 0

&& checkString.charAt(0) == E);

}
}

C_STR008 Do not use system-dependent symbol (\n, \r, etc).


Is literal used in code as line feed code (\n, \r) ? The character and the character string used as
a line feed code are different depends on Operating System. Portability will get worse if literal such
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

public void displayMessage( String message) {

public void displayMessage( String message) {

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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

103/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

Following program shows error margin in double


import java.math.BigDecimal;
public class BigDecimalTest {
public static void main(String[] args) {
double d = 0.0;
BigDecimal b = new BigDecimal("0.0");
for (int i = 0; i < 100; i++) {
d += 0.1;
b = b.add(new BigDecimal("0.1"));
}
System.out.println("double:" + d);
System.out.println("BigDecimal:" + b.toString());
}
}
Program execution result
double:9.99999999999998
BigDecimal:10.0

Updated

3/9/2006

By
By

104/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

C_NUM002 Consider the precision when comparing number


Do you aware the precision of numerical values when comparing them? The rounding error occurs
Explanation /
Motive

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

public class BadSample {

In an application in which rounding error may happen,


use BigDecimal instead of double and float,

void method(double value) {


if (value == 100){

or use equals() method of floating decimal point

System.out.println("value=100");

wrapper class such as Double and Float for

} 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

The following program casts double type number to int type.


public class CastTest{
public static void main(String[] args){
double doubleType = 2.75;
int intType = (int)doubleType; \\ cast double to int
System.out.println("double : " + doubleType);
System.out.println("int : " + intType);
}
}
Result
double : 2.75

Updated

3/9/2006

By
By

105/163
Teguh

Phase

Project Name

Block Name
Document Name
int : 2

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

106/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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 {

public class BadSample {

public static void main(String[] args){

public static void main(String[] args){

int length = 3;

int length = 3;

long[] times = new long[length];

Date[] dates = new Date[length];

for(int i = 0; i < length; i ++){

for(int i = 0; i < length; i++){

times[i] = System.currentTimeMillis();

Calendar now = Calendar.getInstance();

System.out.println(times[i]);

dates[i] = now.getTime();

long time = dates[i].getTime();


System.out.println(time);

}
}

}
}

Execution result ( executed at the same time with

left sample)

Execution result

1078115074691

1078115074691

1078115074701

1078115074701

1078115074701

1078115074701

Explanation

Explanation

We can get same result with left sample by using

Current time can be represented in milisecond

System.getCurrentTimeMillis()

(calculated from 1970/1/1 00:00:00 GMT).

Long value of time can be converted to Date object

That value can be obtained by using getTime() method

Calendar cal = Calendar.getInstance();

of Date class

cal.setTimeInMillis(time);

Updated

3/9/2006

By
By

107/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

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

TMAP Application Standard

TMAP Development Standard

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.*;

public class BadSample {

public class FixedSample {

public static void main(String[] args){

public static void main(String[] args){

Vector sampleVector = new Vector();

List sampleList = new ArrayList();

sampleVector.addElement(1);

sampleList.add(1);

sampleVector.addElement(2);

sampleList.add(2);

sampleVector.addElement(3);

sampleList.add(3);

Enumeration sampleEnumeration =

Iterator sampleIterator =sampleList.iterator();

sampleVector.elements();

while (sampleIterator.hasNext()) {

while (sampleEnumeration.

System.out.println( sampleIterator.next());

hasMoreElements()) {

System.out.println(

sampleList.remove(1);

sampleEnumeration.nextElement());

int length = sampleList.size();

for (int i = 0; i < length; i++) {

sampleVector.removeElement(1);

System.out.println( sampleList.get(i));

int length = sampleVector.size();

for (int i = 0; i < length; i++) {


System.out.println(
sampleVector.elementAt(i));
}
}

}
}

Updated

3/9/2006

By
By

109/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

Sample of HashMap which only handles String object


public class StringHashMap {
private HashMap map = new HashMap();
public void put( String key, String value ){
map.put( key, value );
}
public String get( String key ){
return (String)map.get(key);
}
.
}
There are various method to do this, such as declare class which has general method as super class, then
extend it. Think about design of class which is easy to extend. It is necessary to define new one because
argument and return value are in Object type when implementing Collection class of JDK standard package.

Updated

3/9/2006

By
By

110/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

111/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

Stream is not closed when exception occurs

If we write close() method in finally block, stream will

public class BadSample {

certainly be closed even if exception occurs.

public void badSampleMethod( File file) {

public class FixedSample {

try {

public void fixedSampleMethod( File file) {

new BufferedReader(new FileReader(file));

BufferedReader reader = null;

reader.read();

try {

reader.close();

reader = new BufferedReader(

} catch (FileNotFoundException fnfe) {

new FileReader(file));

fnfe.printStackTrace();

reader.read();

} catch (IOException ioe) {

} catch (FileNotFoundException fnfe) {

ioe.printStackTrace();

fnfe.printStackTrace();

} catch (IOException ioe) {

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_STM002 Use reset() method for ObjectOutputStream


Call reset() method properly in a method which uses ObjectOutputStream object.
The ObjectOutputStream class keeps having the reference to all written objects until reset() is
called. These objects are never collected by GC until the reset() method is called. There is
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public classFixedSample {

public void writeToStream(Object input)

public void writeToStream(Object input)

throws IOException {

throws IOException {

ObjectOutputStream stream =

ObjectOutputStream stream =

new ObjectOutputStream( new

new ObjectOutputStream( new

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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

114/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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.*;

public class BadSample{

public class FixedSample {

public void badSampleMethod( File file) {

public void fixedSampleMethod( File file) {

BufferedReader reader = null;

BufferedReader reader = null;

try {

try {
reader = new BufferedReader(

reader = new BufferedReader(

new FileReader(file));

new FileReader(file));

reader.read();

reader.read();

} catch (Exception e) {

} catch (FileNotFoundException fnfe) {

e.printStackTrace();

fnfe.printStackTrace();

} finally {

} catch (IOException ioe) {

try{

ioe.printStackTrace();
reader.close();

} finally {

} catch (Exception e2) {

try{

e2.printStackTrace();

reader.close();

} catch (IOException ioe2) {

ioe2.printStackTrace();

}
}

Updated

3/9/2006

By
By

115/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

public class BadSample {

Recommended Sample
public class FixedSample {

public void badSampleMethod() throws Exception {

public void fixedSampleMethod ()

throw new Exception();

throws NoSuchMethodException {

throw new NoSuchMethodException ();

}
}

C_EXT003 In catch block, be sure to do error handling


Perform error handling in catch block, do not left it blank. We write catch statement because we
want to perform necessary handling when exception is thrown. It can lead to bugs if nothing is
Explanation /
Motive

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.*;

public class BadSample{

public class FixedSample {

public void badSampleMethod( File file) {

public void fixedSampleMethod( File file) {

BufferedReader reader = null;

BufferedReader reader = null;

try {

try {
reader = new BufferedReader(
new FileReader(file));
reader.read();

} catch (FileNotFoundException fnfe) {

reader = new BufferedReader(


new FileReader(file));
reader.read();
} catch (FileNotFoundException fnfe) {

Updated

3/9/2006

By
By

116/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

fnfe.printStackTrace();
} catch (IOException ioe) {

} catch (IOException ioe) {


ioe.printStackTrace();

} finally {

} finally {

try{

try{
reader.close();

reader.close();

} catch (IOException ioe2) {

} catch (IOException ioe2) {

ioe2.printStackTrace();
}

C_EXT004 Do not extend Error and Throwable class


Do not define subclass of Error class. Error class indicates a critical problem that should not be
caught in application. Therefore, do not define subclass of Error class in application. Exception
defined in application should extend Exception class.
Moreover, do not define the subclass of Throwable. Throwable class is a super-class of
Explanation /
Motive

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

public class BadSampleException extends Error {

Recommended Sample
public class FixedSampleException

extends Exception {

public class AnotherBadSampleException


extends Throwable {
}

Updated

3/9/2006

By
By

117/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_EXT005 Do not define exception class without purpose.


Use exception included in JDK standard package as far as possible. Define new exception only
when exception in application can not be represented by the one included in JDK standard

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

public class InputOutputException extends Exception {

It is not necessary to define InputOutputException class

public InputOutputException( String sample) {


super(sample);

as written in left column because we can use


IOException class included in JDK standard package.

Also do not define exception which only has specific

function as shown in SampleClassABCMethod-

public class SampleClassABCMethodException

Exception in left column.

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

public class BadSample {


public int sampleMethod(int value){
int a = value;
try{
if( a == 1 ){
return a;

Updated

3/9/2006

By
By

118/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

120/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

A.3.24. Garbage Collection


C_GC001 call super.finalize() when overriding finalize()
Do you call super.finalize() when overriding finalize() ? finalize() method is a method used by
Explanation /
Motive

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

public class BadSample {

Recommended Sample
public class FixedSample {

protected void finalize() throws Throwable {

protected void finalize() throws Throwable {

super.finalize();

}
}

C_GC002 Do not call finalize() in application


Do you call finalize() method? finalize() is automatically called by garbage collector when
objects are collected. If finalize() is called explicitly, it will be called again by garbage collector.
Explanation /
Motive

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.*;

public class BadSample {

public class FixedSample {

private FileInputStream stream = null;

private boolean released = false;

public void finalize() throws Throwable {

private FileInputStream stream = null;

if(stream != null){
stream.close();
}
super.finalize();
}

public synchronized void release()


throws Throwable{
if (!released) {
if(stream != null){
stream.close();

Updated

3/9/2006

By
By

121/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Function Name

Coding Conventions

Title

private FileInputStream stream = null;

Created
A. Java Coding Convention

released = true;

public class BadTest {

private BadSample sample = new BadSample();

void cleanup() throws Throwable {

public void finalize() throws Throwable {

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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

123/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

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

in all classes because it is defined in java.lang.Object class. However java.lang.CloneNot


SupportedException will be thrown if Cloneable interface is not implemented.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class FixedSample implements Cloneable{

public Object clone(){

public Object clone(){

try{

try{
return super.clone();

return super.clone();

}catch(CloneNotSupportedException e){

}catch(CloneNotSupportedException e){

throw new InternalError(e.getMessage());

throw new InternalError(e.getMessage());

public static void main( String[] args) {

public static void main( String[] args) {

CloneSample sample = new CloneSample();

CloneSample sample = new CloneSample();

sample.clone();

sample.clone();

}
}

}
}

Updated

3/9/2006

By
By

124/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
A. Java Coding Convention

C_MISC002 Use intanceof in casting process


Casting process can only be performed between classes which have inheritance relation.
Explanation /
Motive

If class which doesn't have inheritance relation is included in casting objects, check using
instanceof.
Not Recommended Sample

public class BadSample {

Recommended Sample
public class FixedSample {

public void badSampleMethod( Object object){

public void fixedSampleMethod( Object object){

Parent parent = (Parent)obj;

if (object instanceof Parent) {

Parent parent = (Parent)obj;

}
}
}

Updated

3/9/2006

By
By

125/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
A. Java Coding Convention

Updated

3/9/2006

By
By

126/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

B. Batch Coding Convention


B.1 Coding Style
B.1.1. Batch Header Section
This section consists of the batch header information. The header shall be in following formats
/************************************************************************************************
* Program History :
*
* Project Name

: TOPS

* Client Name

: TOYOTA

* Program Id

: BTOPSL01.pc

* Program Name : Common utility Program


* Description
*
* Environment

: This program contains all the Library functions used in


the TopServ Application.
: Sun Solaris Ver 5.9/Oracle Release 9.2.0.1.0

* Language

: Pro*C/C++ Release 9.2.0.1

* 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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

B.1.2. Include Section


This section consists of include declaration for all the header files used by the batch.
/******************************************************************************/
/* System header files.

*/

/******************************************************************************/
#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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
B. Batch Coding Convention

Updated

3/9/2006

By
By

129/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

B.1.3. Global Variables Section


This section consists of all the global variables used in the batch.
/******************************************************************************/
/* Declare Global Variables

*/

/******************************************************************************/
FILE_TYPE gs_FileInfo;
FILE

* gfp_Data = NULL;

struct struct_HEADER gst_HDR ;


char

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];

/* Batch execution status */

B.1.4. Extern Variables Section


This section consists of all the external variables used in the batch.
/********************************************************************************/
/* Declare Extern Variables

*/

/********************************************************************************/
extern char xs_SubmitTm[]; /* Submit Time to be used in updProcCtrl */
extern int

xn_PID

extern char xs_User[]

; /* ProgramID to be used in logFile

*/

; /* User to be used to update Database

*/

B.1.5. Main Function Section


This section consists of main function used in the batch. The main function defined the
Start of batch , database connection and processes the batch and end of batch.

Created
B. Batch Coding Convention

Updated

3/9/2006

By
By

130/163
Teguh

Phase
Block Name
Document Name

Project Name

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
B. Batch Coding Convention

Updated

3/9/2006

By
By

131/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
C. SQL Coding Convention

3/9/2006

Updated

C. SQL Coding Convention


C.1. Coding Styles
The SQL description style should comply with the following rules in the interest of maintainability.
a. Use upper case capital letters
All description should be written in upper case capital letters including database objects such as the table name, field name, view name and SQL functions.
However, use lower case for variables used in embedded SQL such as bind variables.
* Any field names must not be used as variable names
b. Insert carriage return appropriately to divide lines.
When listing fields, use separate lines for each field and indent appropriately.
Use separate lines for each formula for a WHERE clause
Use separate lines for each table in a FROM clause
Use separate lines for each assignment expression for an UPDATE clause.
However, when there are many lines and the above rules make the program difficult to read, a line saving style can be used.
c.

Define an alias for each table


However, it is not always necessary in a SQL statement with a single table.
The alias should be defined in the FROM clause. The first table should be called T1 and followed by T2, T3, T4, .etc..
If there are any abbreviation already determined by each application team, those name may be used.
Example)
SELECT T1.LASTNAME,
T2.NAME,
MAX(T3.SALARY) BEST_SALARY
FROM EMPLOYEE T1,
COMPANY T2,
SALHISTORY T3
WHERE T1.COMPANYID = T2.COMPANYID
AND T1.EMPID = T3.EMPID
AND T1.HIREDATE > ADD_MONTHS(SYSDATE, -60).....;
UPDATE EMPLOYEE
SET HIREDATE = SYSDATE,
TERMDATE = NULL
WHERE DEPTID = 105;
INSERT INTO EMPLOYEE
(EMPID,.....)

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).....;

Document Name UPDATE EMPLOYEE

Coding Conventions

Title

SET HIREDATE = SYSDATE,


TERMDATE = NULL
WHERE DEPTID = 105;
INSERT INTO EMPLOYEE
(EMPID,.....)
VALUES (105,....);

d.

The field names should be described as table_name.field_name format.


However, it is not always necessary in a SQL statement with a single table.

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

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

Created
C. SQL Coding Convention

3/9/2006

Updated

C.2. Coding Rules


C.2.1. Rules on Inquiry Processing
a.

Obtaining the execution plan


Always obtain and evaluate the execution plan (EXPLAIN) for all SQL used.
Note that the access path may drastically change by the number of rows in a table if the Optimizer is configured on a cost basis.

b.

Prohibition on use of sub-queries


In principle, sub-queries should be replaced by association operations as much as possible. They may only be used when the sub-query returns only a few rows.
- In-line view
A sub-query which describes a SELECT clause within a FROM clause.
In principle, this use is prohibited ; replace with an association.
- Nested query
A sub-query in a WHERE clause. A nested sub-query is prohibited.
- Correlation sub-queries
A sub-query which queries fields on a table which is also queried by the sub-query's parent statement.
In principle, this use is prohibited. Use only for tuning sub-queries.

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.

Prohibition of complex query syntax


In principle, CONNECT BY, INTERSECT and MINUS should not be used and should be replaced by logics.
When it is unavoidable, consult the database manager (= the DBA in each application team)

e.

Prohibition on use of SQL statements for complex conditional branching.


* Pro*COBOL R9.2.0 does not support a CASE formula as an embedded SQL statement (supported by Pro*C/C++ R9.2.0)

By
By

134/163
Teguh

Phase

Project Name

Block Name

TMAP Development Standard

Document Name
f.

TMAP Application Standard

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.

Prohibition on use of view association operations


A view should not be associated with other views and tables. Configure a new view when the configuration of an existing view is insufficient.
Also, the use of a view in a sub-query is prohibited.

h.

Prohibition of implicit type conversion


Do not use an implicit type conversion for field value comparison and assignment operations ; always convert explicitly.
Especially for the date type, a TO_DATE/TO_CHAR function should be used and specify and convert the date format explicitly.

i.

The usage of index from a WHERE clause


Note that indexes are not used for the following cases.
- When a function or arithmetic operator is used for the index field.
<Use of index>

WHERE TCFROM = TO_DATE('20030101', 'YYYYMMDD')

<Total table scan>

WHERE TO_CHAR(TCFROM, 'YYYYMMDD') = '20030101'

- Comparison using a NOT condition (!=)


<Total table scan>

WHERE PARTSNUM != 0

- When a NULL is specified for a search condition


<Total table scan>

WHERE STATUS IS NULL

- If anything else but a front concordance is specified in a part concordance search using a LIKE operator
<Use of index>

WHERE ADDRESS LIKE 'FUKU%'

<Total table scan>

WHERE ADDRESS LIKE '%OKA'

Obtain and valuate the execution plan because the usage of indexes changes by various conditions.
j.

Prohibition on use of SELECT *


Always specify field names for the field list in a SELECT statement

k.

Restriction on the number of tables for an association

3/9/2006

By
By

135/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
C. SQL Coding Convention

Updated

The number of tables for an association operation should be limited to 3.


Associating many tables may impact performance. Consider denormalization and use of the Materialized View.
When it is considered that use of the Materialized View is necessary, consult the database managers.
l.

Range query using a BETWEEN clause.


Use BETWEEN when specifying a search condition (.e. equal and more, equal and less, and less), and it is implicitly understood that there are
an upper limit and lower limit, ,

m. Optimize the path when associating multiple tables.


In a SQL sentences which JOIN multiple tables using different fields for association and search conditions, and also if those conditions can be
specified equally in a multiple JOIN, specify the condition on a table with less rows.
n.

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.

Restriction on use of hints


In principle, hints should not be used.
When it is considered that the use of hints is necessary, consult the database managers.

p.

Restriction on use of ROWID


A ROWID para-field should only be used when there is a problem in performance.
Also, descriptions which are depending on the ROWID internal format is prohibited.

q.

Use of SQL cache


The following are the rules to re-use SQL statements which are cached in the shared buffer.
- Strictly follow the coding rules.
- Avoid using dynamic SQL. Also avoid SQL statement generation by linking character arrays.
Use PreparedStatement for Java (JDBC)
Use bind variables for an embedded SQL.
- Frequently used SQL statements should be made into views.

3/9/2006

By
By

136/163
Teguh

Phase

Project Name

Block Name

TMAP Development Standard

Document Name

r.

TMAP Application Standard


Coding Conventions

Page

Function Name
Title

Created
C. SQL Coding Convention

Use of the ANSI SQL:1999 association syntax


* Pro*C/C++ R9.2.0 and Pro*COBOL R9.2.0 do not support the ANSI combined syntax in embedded SQL statements.

Updated

3/9/2006

By
By

137/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Coding Conventions

Page

Function Name
Title

Created
C. SQL Coding Convention

Updated

C.2.2. Rules on Update Processing


a.

Acquisition of an execution plan is essential


Obtain the execution plan and carry out the tuning on sub-queries in the INSERT clause and UPDATE clause as well as the SELECT clause.

b.

Field specification in an INSERT clause


Always specify the target fields in INSERT clauses. Avoid using SELECT * FROM in sub-queries and specify the field names.

c.

Deleting entire table


Use a TRUNCATE clause when deleting all rows in a table.

d.

Updatable ResultSet should not be used (JDBC).


Always issue a SQL statement (INSERT/UPDATE/DELETE) for a ResultSet update for better performance.

C.2.3. Transaction Rules


a.

Avoiding explicit locks


It is desirable to regulate competition between applications in order to run processes within the ORACLE default lock mechanism.

b.

Strictly follow the lock order


Reduce the possibility of a deadlock by establishing a rule for the order to lock tables.
However, note that a lock is activated when the table is accessed rather than when it is specified.

c.

NOWAIT for locks


Always specify the NOWAIT option when an explicit lock is used.

d.

Use of table locks


Table locks should not be used unless most of the data in a table is subject to an update.

3/9/2006

By
By

138/163
Teguh

Phase

Project Name

Block Name

TMAP Application Standard

TMAP Development Standard

Document Name

Page

Function Name

Coding Conventions

Title

D. Shell Script Coding Convention


D.1 Coding Style
D.1.1 Header Comment
The header comment shall contain items described in example below.
# ************************************************************************************************
# * Program History :
#*
# * Project Name

: TOPS

# * Client Name

: TOYOTA

# * Program Id

: BTOPSL01.ksh

# * Program Name : Upload File Program


# * Description
# * Environment

: This program is used to upload PSMS file into Database


: Sun Solaris Ver 5.9/Oracle Release 9.2.0.1.0

# * Language

: Korn shell scripting languange

# * 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

TMAP Application Standard

TMAP Development Standard


Coding Conventions

Page

Function Name
Title

Created
D. Shell Script Coding Convention

Updated

3/9/2006

By
By

140/163
Teguh

PL/SQL & SQL Tips


Rank
***

1. 1. Specify column name in an insert.


INSERT INTO emp VALUES(1, 'abc');
INSERT INTO emp(id, nm) VALUES(1, 'abc');

***

---- NG!
---- OK!

2. Code "ROLLBACK" at first in exception.


EXCEPTION
WHEN OTHERS THEN
Pk_Logger.writeDetailToDB(.....

->

EXCEPTION
WHEN OTHERS THEN
ROLLBACK;

ROLLBACK;

Pk_Logger.writeDetailToDB(.....

END;

3. Do not specify columns, when using "EXISTS" condition.


It's enough by fixed value.
SELECT e.id, e.name
FROM emp e
WHERE EXISTS
(SELECT d.dept_cd -- no need
FROM dept d
WHERE e.dept_cd = d.dept_cd);

END;

4.

->

SELECT e.id, e.name


FROM emp e
WHERE EXISTS
(SELECT 'x'
FROM dept d
WHERE e.dept_cd = d.dept_cd);

Let's use CASE. (new function of Oracle9)


IF rec.ID = 'A'
product_code := 10;
ELSIF rec.ID = 'B'
product_code := 20;
ELSIF rec.ID = 'C'

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;

---- NG!(Does not use index, for using calculation.)


---- OK!(Uses index)

select .... where TO_NUMBER(COL) = :VAL;


select .... where COL = TO_CHAR(:VAL);

---- NG!(Does not use index, for using function.)


---- OK!(Uses index)

select .... where COL != :VAL;

---- NG!(Does not use index, for using "!=".)

select .... where NVL(COL) = :VAL;

---- NG! As much as possible, don't use NVL. Check a specification.


It isn't need absolutely to primary key.

<< 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

DEPT_CD = 1 and NAME = 'SMITH' and AGE = 25;


NAME = 'SMITH' and AGE = 25 and DEPT_CD = 1;
DEPT_CD = 1 and NAME = 'SMITH' and AGE > 25;
DEPT_CD = 1 and NAME = 'SMITH';
DEPT_CD = 1 and AGE = 25;

OK!(Uses
OK!(Uses
OK!(Uses
OK!(Uses

index)
index)
index)
index)

select .... where DEPT_CD = 1 and NAME IS NULL;


select .... where DEPT_CD IS NULL and NAME = 'SMITH';

---- OK!(Uses index)


---- NG!(Does not use index, for using "IS NULL" to first column.)

select .... where DEPT_CD = 1 and AGE = 25 or AGE = 26;


select .... where DEPT_CD = 1 and AGE = 25 or AGE = 26;

---- NG!(Does not use index, for using "or".)

How to check SQL by PL/SQL Developer


1. Open Explain Window.
[File] - [New] - [Explain Plan Window]
2. Paste SQL to Window

How to check SQL by script


Execute the following script in SQL*Plus
DELETE FROM PLAN_TABLE;
EXPLAIN PLAN FOR
select * from Z_TEST_TBL2
where DEPT_CD = 1 and NAME = 'SMITH' and AGE = 25;

CHECK SQL

->

SELECT DECODE(ID,0,'',LPAD(' ',2*(LEVEL-1))||LEVEL||'.'||POSITION)||


' '||OPERATION||
' '||OPTIONS||
' '||OBJECT_NODE||
' '||OBJECT_NAME||
' '||OBJECT_TYPE||
' '||DECODE(ID,0,'COST='||POSITION) QUERY
FROM PLAN_TABLE
CONNECT BY PRIOR ID = PARENT_ID
START WITH ID = 0
ORDER BY ID;

Inex search

DELETE FROM PLAN_TABLE;


EXPLAIN PLAN FOR
select * from Z_TEST_TBL2
where DEPT_CD = 1 and NAME = 'SMITH' or AGE = 25;
SELECT DECODE(ID,0,'',LPAD(' ',2*(LEVEL-1))||LEVEL||'.'||POSITION)||
' '||OPERATION||
' '||OPTIONS||

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
->

Table full scan!

Table full scan!


' '||OBJECT_NODE||
' '||OBJECT_NAME||
' '||OBJECT_TYPE||
' '||DECODE(ID,0,'COST='||POSITION)
FROM PLAN_TABLE
CONNECT BY PRIOR ID = PARENT_ID
START WITH ID = 0
ORDER BY ID;

QUERY

6. Use ROWID
SELECT empno, sal FROM EMP
WHERE id = :id
FOR UPDATE NOWAIT;
:
:

->

UPDATE EMP SET sal = sal * 1.2


WHERE ID = id;

***

SELECT empno, sal, rowid FROM EMP


WHERE id = :id
FOR UPDATE NOWAIT;
:
:
UPDATE EMP SET sal = sal * 1.2
WHERE rowid = :rowid;

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;

8. BULK BIND INSERT


CREATE TABLE TEST_TBL(
C1 NUMBER(4),
C2 VARCHAR2(10)
)

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
:
:
:

->

-- NORMAL INSERT ----------------------FOR i IN tbl_c1.FIRST..tbl_c1.LAST LOOP


INSERT INTO TEST_TBL(c1, c2) VALUES(tbl_c1(i), tbl_c2(i));
END LOOP;

-- BULK BIND INSERT ---------------------FORALL i IN tbl_c1.FIRST..tbl_c1.LAST


INSERT INTO TEST_TBL(c1, c2) VALUES(tbl_c1(i), tbl_c2(i));

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

<-- 210,000 + 10,000


<-- 100,000 + 20,000
<-- INSERT

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

Page 159 / 163


By
FJCL) Ishikawa
By
FJ Tsukamoto

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

Revised DB2 Standards.doc


EXPLAIN access path check (standard)
Where SQL has been chosen, EXPLAIN must be obtained in the stand-alone test phase to check
the access path.
Where the following conditions are met on the basis of the EXPLAIN check, an SQL review is
normally required.
ACCESSTYPE=I and MATCHCOLS=0
ACCESSTYPE=R (except for very small tables and external tables)
Where PLAN/PACKAGE is bound in the actual environment, the EXPLAIN(YES) option must be

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

As per right-hand column

SQL statement descriptions should be no larger than 25 KB including blank portions.

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

multiple SQL statement descriptions, the same statement should be re-used.

(deletion/update not performed), use stand-alone SELECT.


5

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.

As per right-hand column

For read-only processes, specify 'FETCHONLY' in the cursor declaration.

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

Where update can be performed based on the cursor, specify 'FORUPDATEOF'


in the cursor declaration.

As per right-hand column

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.

(COL name 1 is not an index item. An arbitrary item is specified.)

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

No. GSPS/A-TOP standards


10 Where JOIN is used, EXPLAIN results must be obtained and submitted beforehand.
The following standards are normally used for join processing:
N:M join in non-unique columns can be used for up to two tables
1:1 joins for unique columns can be used for up to three tables
Joined columns must be index columns.
Conditions for Joined columns must be specified.
INNER JOIN should be normally used.
LEFT OUTER is normally not allowed.
RIGHT-OUTER/FULL-OUTER is never allowed.

Created
Updated

2003/5/14
2003/11/05

Page 160 / 163


By
FJCL) Ishikawa
By
FJ Tsukamoto

Revised DB2 standards.doc


The following standards are normally applied to join processing:
N:M join in non-unique columns can be used for up to two tables
1:1 joins for unique columns can be used for up to three tables
Joined columns must be index columns.
Conditions for Joined columns must be specified.
All join types may be used (FULL,LEFT,RIGHT-OUTER,INNER).

11

ORDER BY is normally used in accordance with the following standards.


<1> ORDER BY on cluster index columns, where DB2 internal SORT (METHOD) does not occur
<2> Online ORDER BY usage standards where cluster index is not used
- Sum of column sizes for extracted data -- maximum 200 bytes
- Sum of column sizes for SORT key items -- maximum 200 bytes
- Number of records sorted maximum 100 records
(Note that the number of records sorted is the ANSERSET (searched rows) number, not the
FETCH record.)
<3> ORDER BY in BATCH prohibited except for <1> above

ORDER BY is normally used in accordance with the following standards:


ORDER BY on cluster index columns
BATCH and online ORDER BY usage standards where cluster index is not used
Sum of column sizes for extracted data -- maximum 200 bytes
Sum of column sizes for SORT key items -- maximum 200 bytes
Number of records sorted maximum 100 records

12

As per right-hand column

13

As per right-hand column

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

UNION processing allowed where necessary.

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

As per right-hand column

When joining multiple conditions using AND, start with conditions that have a higher filtering ratio.

17

As per right-hand column

When joining multiple conditions using OR, start with conditions that have a lower filtering ratio.

18

As per right-hand column


However, the SQL obtained as a result of rewrite using "JOIN" clause must conform to JOIN rules

'IN(sub-query)' must be performed using JOIN.


SELECT A FROM TB1 WHERE B IN
(SELECT C FROM TB2 WHERE D=:HOSTVAR)

SELECT A FROM TB1,TB2


WHERE TB1.B=TB2.C AND TB2.D=:HOSTVAR

(A-TOP standard No. 10).

The column name must be explicitly stated for INSERT process.

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

No. GSPS/A-TOP standards


19 As per right-hand column

Revised DB2 standards.doc

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

Same as right-hand column when rewriting with UNION ALL


Submission required for rewriting with UNION (A-TOP standard No.14

UNION is used for OR join of index rows and non-index rows.


SELECT * FROM TB1
WHERE A=:HOSTVAR1 OR B=:HOSTVAR2
-SELECT * FROM TB1
WHERE A=:HOSTVAR1
UNION
SELECT * FROM TB1
WHERE B=:HOSTVAR2

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.

Page 161 / 163


By
FJCL) Ishikawa
By
FJ Tsukamoto

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'

SELECT COUNT(*) FROM TB1


WHERE A IN('10','20','30')

22

As per right-hand column

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

As per right-hand column

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'

SELECT COUNT() FROM TB1


WHERE A BETWEEN '100' AND '200'
When the search condition is '> OR <', apply '<>' using the BETWEEN search results.

External Design
Block name
Document name
Phase

Project name
GSPS/A-TOP
C Common
SQL Standards

Function name

Title

Common
SQL Standards

No. GSPS/A-TOP standards


24 Where UPDATE or INSERT is used, the department, user ID, and time of update (TIMESTAMP) must be updated.
TIMESTAMP update is performed using CURRENT TIMESTAMP as follows:
UPDATE tablename SET MTTMSP = CURRENT TIMESTAMP WHERE
(MTTIME is COLUMNNAME for time of update)
(Either BLANK or UNDERSCORE ('_') may be used between CURRENT and TIMESTAMP.)

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

During batch updating, commit should be performed every 1000 records.


Online updates are normally restricted to up to 100 records.

29

Column and host variable attributes must match.

30

NOT may not be used in conditional statements.

31

BETWEEN low-val AND high-val may not be used in 1st MATCHCOLS item.

32

SUBSTR and COLUMN CONCAT should be avoided in predicate.

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

DISTINCT is normally not allowed.

36

TABLE ACCESS order must be followed.

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

DELETE/UPDATE for multiple rows is not performed using direct DELETE/UPDATE.


Select rows using SELECT FOR UPDATE, then perform DELETE/UPDATE CURRENT OF CURSOR.
<1> Main KEY must be used to designate rows for exclusion control and to prevent DEADLOCK.
<2> The above rules must be followed in order to adhere to the 1000 records COMMIT requirement.
Using direct DELETE/UPDATE for multiple row DELETE/UPDATE can cause the number of updates to exceed 1,000 records without warning.
In the worst-case scenario, the DB2 system control value (NUMLKUS = 10,000 records) is exceeded, causing ABEND.
LOCK for update rows is held in DB2 REGION MEMORY.
NUMLKUS is the limit value used to prevent applications from obtaining excessively large LOCK quantities, thus ensuring concurrency among applications.
The 1000 records COMMIT rule is a gentlemen's agreement built into applications as a means of ensuring that the NUMLKUS value is not accidentally exceeded.
Applications that do not observe the 1000 records COMMIT rule put pressure on shared DB2 MEMORY resources, which affects other applications.

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

No. GSPS/A - TOP standard


1 Results of EXPLAIN check

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)

is not generated for ORDER BY on cluster index columns


<2> Online ORDER BY usage standards where cluster index is not used
- Sum of column sizes for extracted data -- maximum 200 bytes
- Sum of column sizes for SORT key items -- maximum 200 bytes
- Number of records sorted maximum 100 records

Created
Updated

Page163 / 163
By
FJCL) Ishikawa
By
IBM Shimizu

EXPLAIN access path check (standard)


Where SQL has been chosen, EXPLAIN must be obtained in the stand-alone test phase to check
the access path.
Where the following conditions are met on the basis of the EXPLAIN check, an SQL review is
normally required.
Index SCAN and #Key Columns = 0
Table SCAN (except for very small tables and external tables)
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.

The following standards are normally used for ORDER BY:


ORDER BY for cluster index columns
BATCH and online ORDER BY usage standards where cluster index is not used
Sum of column sizes for extracted data -- maximum 200 bytes
Sum of column sizes for SORT key items -- maximum 200 bytes
Number of records sorted maximum 100 records

(Note that the number of SORTs is the ANSERSET (searched rows) number, not the FETCH number.

38

2003/5/14
2003/11/20

<3> ORDER BY in BATCH prohibited except for above


DELETE/UPDATE for multiple rows is not performed using direct DELETE/UPDATE.
Define the rows using SELECT FOR UPDATE, then execute DELETE/UPDATE CURRENT OF CURSOR.
<1> Main KEY must be used to designate rows for exclusion control and to prevent DEADLOCK.
<2> The above rules must be followed in order to adhere to the 1000 records COMMIT requirement.
LOCK for update rows is held in Database Global Memory.
The LOCK for the entire database holds up to 10,000 records (the maximum number of records is 1,500 per application).
LOCK restrictions are specified in the database configuration parameters LOCKLIST and MAXLOCKS.
- LOCKLIST: number of LOCKs that can be held in the database (number of pages @ 4 KB per page), standard value = 100/150 (32/64 bit UDB)
- MAXLOCKS: Percentage of LOCKs per application that can be acquired within the LOCKLIST limit, standard value = 15
When applications attempt to acquire more LOCKs than the MAXLOCKS limit, a lock escalation occurs and locks are assigned to individual tables (the LOCKLIST is released).
Applications should be designed to prevent lock escalation and preserve application concurrency.
If an investigation determines that a lock escalation has occurred, the lock range should be coordinated among applications (including SQL review).
The 1000 COMMIT rule is considered a gentlemen's agreement between applications designed to avoid the possibility of lock escalation due to simple errors.
An application that does not conform to the 1000 records COMMIT rule puts pressure on shared DB2 MEMORY resources, which affects other applications.

Você também pode gostar