Good coding style is very important for easy understanding
what your program is about.
Here are some recommendations.
- Comments
- Each Java program must start with a comment block describing what the program is about,
stating the author and the version of the program.
- Methods must be preceded by a comment block in the form:
/*--------------- name of the method ----------------------------*/
// Purpose::
// Input :
// Output:
// Methods used:
/*---------------------------------------------------------------*/
- All declarations within a method/class should be grouped together.
Each should be on a separate line, accompanied
by a comment describing the purpose of the declared variable.
- The code for each basic step in the implemented algorithm should be preceded by a
comment describing the purpose of that code.
Example
The algorithm for computing the average of list of numbers has two steps:
- Finding the sum of all numbers
- Dividing the sum by the number of the elements.
The code should look like this:
// Finding the sum of the elements in the array XXXX
……. Here comes the code that finds the sum
// computing the average
…….. Here comes the code that computes the average
- Identifiers
- Class names start with a capital letter
- Names of methods and variables start with a lower case letter
- Names of constants should be all capital letters
- Names should be meaningful. For example, if your program has a
method that processes withdrawal from a bank account, the name
of the method should be “withdrawal”.
- Composite names are recommended to provide more meaning.
Such names can be form by either writing the second word in the name with a
capital letter, e.g. “checkingAccount”, or using an underscore as a delimiter ,
e.g. “checking_account”.
Whatever option you choose, follow it.
- Curly braces
There are several ways to write curly braces:
while(......){
…..
}
while(......)
{
…..
}
while(......)
{
……
}
Make a choice and stick to it. My personal preference is b).
- Indentation
The code within the curly braces should be indented. Use 2 to 8
spaces for indentation.
- Statements
- There should be only one statement per line
- Statements should be less than 80 characters long
- Operators
Operators should be separated from their operands by a space.
Example:
a = b + c;
do not write a=b+c;
- Constants
Except for 0 and 1, all numerical constants in the program should be named.
Example:
int MAX_SIZE = 1000;
……..
for( i = 0; i < MAX_SIZE; i++)
…….
- Spelling
Your program should have correct spelling.