Download Java coding guidelines

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
PARTool
Coding Policy
Version 0.1
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Revision History
Date
Version
Description
Author
2010-10-17
0.1
Initial Draft
Davor Perić
2010-10-18
0.2
Added section 2 and Review
Inderjeet Singh
2010-10-19
0.3
Added section 3 and 4
Inderjeet Singh
2010-10-19
1.0
Full review and corrections
Arno van lumig
Page 2
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Table of Contents
TABLE OF CONTENTS........................................................................................................................................ 3
INTRODUCTION ............................................................................................................................................... 4
PURPOSE OF THIS DOCUMENT .................................................................................................................................... 4
DOCUMENT ORGANIZATION ....................................................................................................................................... 4
INTENDED AUDIENCE ................................................................................................................................................ 4
SCOPE ................................................................................................................................................................... 4
DEFINITIONS AND ACRONYMS ................................................................................................................................... 4
Definitions ....................................................................................................................................................... 4
Acronyms and abbreviations .......................................................................................................................... 4
1.6REFERENCES ...................................................................................................................................................... 5
PROGRAMMING GUIDE ................................................................................................................................... 6
JAVA CODING GUIDELINES ............................................................................................................................... 7
NAMING CONVENTIONS ............................................................................................................................................ 7
Package names ............................................................................................................................................... 7
Type names ..................................................................................................................................................... 7
Variable names ............................................................................................................................................... 7
Constant names .............................................................................................................................................. 7
Method names ................................................................................................................................................ 7
Abbreviations and acronyms .......................................................................................................................... 7
Programming language .................................................................................................................................. 8
Variable names regarding their scope ............................................................................................................ 8
Implicit object names ...................................................................................................................................... 8
Get/set terms .................................................................................................................................................. 8
Using “is” prefix for Boolean variables and methods ..................................................................................... 8
Names representing a collection of objects .................................................................................................... 8
Exception classes names ................................................................................................................................. 8
STATEMENTS .......................................................................................................................................................... 9
Imported classes ............................................................................................................................................. 9
Classes and interfaces ..................................................................................................................................... 9
Variables ......................................................................................................................................................... 9
Loops ............................................................................................................................................................... 9
Conditionals .................................................................................................................................................... 9
Miscellaneous .............................................................................................................................................. 10
LAYOUT ............................................................................................................................................................... 10
Block Indentation .......................................................................................................................................... 10
Class and interface declaration indentation ................................................................................................ 10
if else class of statement indentation .......................................................................................................... 11
WHITE SPACES ..................................................................................................................................................... 11
COMMENTS .......................................................................................................................................................... 12
Page 3
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Introduction
Purpose of this document
The purpose of this document is to provide guidelines and explanations about general policies and rules
that will be used during the project work on PARTool. Each team member should read this document in detail so
when he starts programming he can use described conventions. Also each member should have this document
opened when he is coding so he can adapt easily into these conventions. Keeping the sanctity of these standards
and guidelines would help the user get the best performance for their applications developed or maintained in
Java.
Document organization
The document is organized as follows:



Section 1, Introduction, describes contents of this guide and main purpose of this document.
Section 2, Programming guide
Section 3, Java coding guidelines, some useful advices for good programming in Java
Intended Audience
The intended audience is:
 All team members of the PARTool project.
 Supervisor of the PARTool project.
Scope
The scope of this document is limited just to this project. It specifies the guidelines for coding in Java
language only and includes standards for Java programming language such as names, indentations, package
names, language of programming (English) etc.
Definitions and acronyms
Definitions
Keyword
Definitions
Acronyms and abbreviations
Acronym or
abbreviation
Definitions
Page 4
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
1.6 References
[1] Java Programming Style Guidelines: http://geosoft.no/development/javastyle.html
[2] Eight Secrets of Successful Programmers: http://www.merrioncomputing.com/Programming/7Secrets.htm
Page 5
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Programming Guide
The programming guide will basically explain some points which which will improve quality of code
and increase understandability [2].
2.1. Code for Human consumption
This gives more emphasis to code for clarity, over efficiency and speed. High level languages were
introduced to help human to understand and write code efficiently. Otherwise a computer works at the bit level
which is not intuitive to humans.
2.2. Comment often and well
Comments help the coder and other developers to understand the code. The main aim of comments is
to tell what the programs do. The correct way for commenting about class/method is what it doing rather than
how. It should be in the language understandable by everyone related to project which is English in our case.
2.3. Layout Code to increase legibility
It helps in increasing the readability of the code. Good indentation helps in finding small problems like
code branch start/end and repetition etc.
2.4. Expect the unexpected and deal with it
Checks before using something for example before you open file make sure it exists, before using
object make sure it is present. It's all about finding ways that can cause your code to fail.
2.5. Name your Variables to aid readability
There are many different ways to name variable, the key is to maintain the consistency and be
informative. Using different conventions could decrease clarity.
2.6. Keep your functions and subroutines simple
A function and subroutine should be only focused on one thing, and one thing only. It is better to divide
the work between different functions, which helps in reusing the same function again and again. The change in
scope of code is easily noticed.
2.7. Scope function and variable appropriately
Try to keep the scope of variables limited, and only provide access to modules that require it. This will
help reduce debugging time.
2.8. Never stop listening and learning
Keep an eye out for new opinions and methodologies and to evaluate them in an impartial and rational
way.
Page 6
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Java coding guidelines
Naming conventions
Each name should be understandable for the programmer and related to the domain for which the system is
being developed.
Package names
All code should be in the dsd.partool.* package or a subpackage.
Type names
Names representing types must be nouns and written in mixed case starting with upper case.
Agent, SubscriberProfile
Variable names
Variable names must be written in mixed case starting with lower case. This makes it easy to distinguish
variables from types and effectively resolves potential naming collision as in the declaration Agent agent.
agent, subscriberProfile
Constant names
Names representing constants (final variables) must be all upper case using underscore to separate words. In
general, the use of such constants should be minimized. In many cases implementing the value as a method is a
better choice:
int getMaxIterations() // NOT: MAX_ITERATIONS = 25
{
return 25;
}
This form is better to read and it ensures a uniform interface towards class values.
MAX_NUMBER_OF_SMS, MAX_CALL_DURATION
Method names
Names representing methods must be verbs and written in mixed case starting lower case. This is identical to
variable names, but methods in Java are already distinguishable from variables by their specific form.
getName(), computeTotalCallDuration()
Abbreviations and acronyms
Abbreviations and acronyms should not be upper case when used as name.
exportHtmlSource(); // NOT: exportHTMLSource();
openDvdPlayer();
// NOT: openDVDPlayer();
Programming language
All names should be written in English.
Page 7
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Variable names regarding their scope
Variables with a large scope should have descriptive names; variables with a small scope can have short names.
Scratch variables used for temporary storage or indices are best kept short. A programmer reading such
variables should be able to assume that its value is not used outside a few lines of code. Common scratch
variables for integers are i, j, k, m, n and for characters c and d.
Implicit object names
The name of the object is implicit and should be avoided in a method name.
line.getLength();
// NOT: line.getLineLength();
Get/set terms
The terms get/set must be used where an attribute is accessed directly.
agent.getName();
agent.setName(name);
Using “is” prefix for Boolean variables and methods
Using the is prefix solves a common problem of choosing bad boolean names like status and flag. isStatus or
isFlag simply does not fit and the programmer is forced to choose more meaningful names. Setter methods for
boolean variables must have set prefix as in:
Void setFound(boolean isFound);
There are few alternatives to the is prefix that fit better in some situations. These are for example has, should
and can prefixes:
boolean canEvaluate();
boolean shouldAbort = false;
Names representing a collection of objects
The plural form should be used on names representing a collection of objects. This enhances readability since
the name give the user an immediate clue of the type of the variable and the operations that can be performed on
its elements.
Collection<CallType> callTypes;
Exception classes names
Exception classes should be suffixed with Exception. Exception classes are not really part of the main design of
the program, and naming them like this makes them stand out relative to the other classes.
class AccessException extends Exception
{
:
}
Statements
Page 8
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Imported classes
Imported classes should always be listed explicitly. Importing classes explicitly gives an excellent
documentation value for the class at hand and makes the class easier to comprehend and maintain.
import java.util.List;
// NOT: import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
Classes and interfaces
Class and interface declarations should be organized in the following manner:
1. Class/Interface documentation.
2. class or interface statement.
3. Class (static) variables in the order public, protected, package (no access modifier),
private.
4. Instance variables in the order public, protected, package (no access modifier),
private.
5. Constructors
6. Methods
Variables
To ensure that variables are valid at any time, they should be initialized where they are declared and they should
be declared in the smallest scope possible. Also, variables never must have dual meaning which enhances
readability by ensuring all concepts are represented uniquely and reduces chance of error by side effects.
Loops
Only loop control statements must be included in the for() construction. This increases maintainability and
readability, and also make clear distinction of what controls and what is contained in the loop.
sum = 0;
for (i = 0; i < 100; i++)
sum += value[i];
// NOT: for (i = 0, sum = 0; i < 100; i++)
sum += value[i];
Loop variables should be initialized immediately before the loop.
isDone = false;
while (!isDone) {
:
}
// NOT: bool isDone = false;
//
:
//
while (!isDone) {
//
:
//
}
do-while loops are less readable than ordinary while loops and for loops since the conditional is at the bottom of
the loop. The reader must scan the entire loop in order to understand the scope of the loop. In addition, dowhile loops are often not needed. Any do-while loop can often be rewritten into a while loop or a for loop.
Reducing the number of constructs used enhance readbility.
Conditionals
The nominal case should be put in the if-part and the exception in the else-part of an if statement. This approach
makes sure that the exception does not obscure the normal path of execution. This is important for both the
readability and performance. The conditional should be put on a separate line.
boolean isOk = readFile(fileName);
// NOT: if (isOK) doCleanup();
Page 9
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
if (isOk) {
doCleanup();
}
else {
:
}
Executable statements in conditionals must be avoided because they are very difficult to read.
InputStream stream = File.open(fileName, "w");
if (stream != null) {
:
}
// NOT:
if (File.open(fileName, "w") != null)) {
:
}
Miscellaneous
The use of magic numbers in the code should be avoided, numbers other than 0 and 1 should be declared as
named constants instead. If the number does not have an obvious meaning by itself, the readability is enhanced
by introducing a named constant instead.
private static final int MAX_CALL_DURATION = 1000;
:
Subscriber[] subscribers = new Subscriber[MAX_CALL_DURATION];
// NOT: Subscriber[] subscribers = new Subscriber[1000];
Layout
This section will explain the indentation style to use while coding.
Block Indentation
Block layout should start from the statement; it increases the readability of code
The appropriate way to indent a small block of code is:
while (!done) {
doSomething();
done = moreToDo();
}
Class and interface declaration indentation
Usage of blocks is a little different from classes and methods than other blocks of code. In classes and
methods the block should start from the declaration.
Correct manner:
class Rectangle extends Shape
implements Cloneable, Serializable
{
...
Page 10
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
}
if else class of statement indentation
Set of statement should be in one block, block format should be same as explaind above in section
3.3.1.
if (condition) {
statements;
}
if (condition) {
statements;
}
else {
statements;
}
3.3.4
Try catch statement
try {
statements;
}
catch (Exception exception) {
statements;
}
finally {
statements;
}
White Spaces
In the code, you should use some white space when required to keep the code clean. Some important
points to consider are:
1.
2.
3.
4.
Operators should have the white spaces before and after;
Java reserved words should have white spaces;
Commas and colons should be followed by white spaces;
Semicolons should also have white spaces.
Some example of above defined points is:
a = (b + c) * d; // NOT: a=(b+c)*d
while (true) {
...
// NOT: while(true){
doSomething(a, b, c, d);
case 100 :
// NOT: doSomething(a,b,c,d);
// NOT: case 100:
for (i = 0; i < 10; i++) {
// NOT: for(i=0;i<10;i++){
Page 11
PARTool
Coding Policy
Version:
0.1
Date: 2010-10-17
Comments
This section is all about the commenting in code, how and when to comment. Comments are normally put
before the statement and must be in English. Some points that need to keep in mind before commenting
1. Block of comments should be avoided
2. Comment should be placed one line above the statement.
In java comment format is like this;
/**
* Return lateral location of the specified position.
* If the position is unset, NaN is returned.
*/
It start with /** and ends with */.
Page 12