Good coding style
Writing code is like writing poetry. Everyone has their own style, but the bottom line is that people should enjoy reading it.
Some general advice on good coding style
Good code is self-explanatory – the need for comments should be minimal. Comments should be added to those parts of the code where explanations are needed.
With code one should not be clever if it is not necessary – do things in an obvious straightforward way. Of course, more efficient code is preferrable to less efficient code.
Good code organization is achieved by organizing the code in small units (classes/methods/functions) that do one thing and that can be reused throughout the code.
Good code can be read and understood in a short amount of time with minimal thinking. One can achieve this (provided that the code functions) by iterating the following: rewrite, rename, edit, and refactor.
Testing is an integral part of coding and good code is well-tested. Test code is the right place to explain how the functional code should be used (and how it should not be used).
Some more specific advice on good coding style
Code formatting:
- Indent your code so that it corresponds to the logical structure of the program. (If you edit your code in a Java programming environment, the pretty printer will already take of the layout.)
Bad example:
for(int i=0; ... )
for(int j=0; ... )
if(i<j)
...
Good example:
for(int i=0; ... )
for(int j=0; ... )
if(i<j)
...
- Try to create a good measure of vertical density of your code (new lines between commands) and keep it consistent
Bad example:
public static int MethodX()
{ int pointX; int pointY; int pointZ;
...
return pointX+pointY+pointZ; }
public static int MethodY()
{ ... }
Good example:
public static int MethodX(){
int pointX; // comment ...
int pointY; // comment ...
int pointZ; // comment ....
...
return pointX+pointY+pointZ;
}
public static void MethodY(){
...
}
Variables:
- Use meaningful variable names. The name should reveal the usage intent.
Bad example:
int cMX;
Good example:
int currentMax;
- If the variable name does not sufficiently describe the usage intent, comment on the variable at its declaration.
Good example:
int k; // counter that ranges from i to j
- It is a good practice to declare variables that are used globally in a method, at the beginning of the method.
Bad example:
public static void MethodX(Matrix X, Matrix Y){
// doing something 1
Matrix tmpMatrix = operationMatrix(X,Y);
// doing something 2
Matrix productMatrix = operationMatrix(X,tmpMatrix);
...
}
Good example:
public static void MethodX(Matrix X){
Matrix tmpMatrix; // obtained by operationMatrix on X and Y
Matrix productMatrix; // obtained by operationMatrix on X and tmpMatrix
// doing something 1
tmpMatrix = operationMatrix(X,Y);
// doing something 2
Matrix productMatrix = operationMatrix(X,tmpMatrix);
...
}
- For local variables the scope of the variable should always be as small as possible.
Good example:
int m=1; // minimal m when sorting takes >5 sec for array of size 10^m
for(; m<MAX_M; m++){
int A[]; // random array
long startTime; // start time
long estimatedTime; // current time - start time
...
}
- It is a good practice to declare a global variable for each parameter of the method that is given as a concrete value.
Bad example:
public static void MethodX(){
...
for (... ;i<15; ...)
for (... ;j<7; ...)
...
}
Good example:
public static int FIRST_ITERATION = 15;
public static int SECOND_ITERATION = 7;
public static void MethodX(){
...
for (... ;i<FIRST_ITERATION; ...)
for (... ;j<SECOND_ITERATION; ...)
...
}
Methods/Functions:
Use meaningful variable names – they should be self-explanatory.
Ideally, one method should do one thing.
Refactor your code by creating methods from blocks that logically do one thing.
Bad example:
public static void Task21(){
// minimal m when sorting takes >5 sec for array of size 10^m
// compute matrix of running times
// compute average
}
Good example:
public static int findMinM(){ ... }
public static long [][] generateMatrixOfRunnintTimes(int m){ ... }
public static long [] computeAverage(long [][] runningTimes){ ... }
public static long [] Task21(){
int m = findMinM();
long [][] runningTimes = generateMatrixOfRunnintTimes(int m);
long [] avgTimes = computeAverage(runningTimes);
// do the rest ...
}
- Ideally, a method should return new values by changing given arguments.
Testing:
Every method written should be tested (even the most trivial one).
The test should be done in a way that exemplifies the use of code.
We recommend that for each developed class one develops a corresponding testing class where each method is tested using one or more methods.
Be suspicious when testing – test for expected outputs but also for unexpected outputs.
Good example:
public static void testFindInSortedArray(){
int [] array = { -11, -3, -1, 2, 8, 11, 15, 23};
// Here we expected that method finds the element with index 6
System.out.println(findInSortedArray(array,15));
// Here the method should return not found (-1)
System.out.println(findInSortedArray(array,3));
}
Commenting Code:
Writing comments is an integral part of the coding – use both multi-line comments (e.g., /* */) and in-line comments (e.g., //) where needed.
Do not over-comment your code – find a good balance.
Bad example:
/* this is the main method where our program starts*/
public static void main(String[] args) {
...
}
- Avoid leaving code lines that are commented out in the final version of your code.
Bad example:
// methodTryThis(3);
// methodTryThat(4);
// methodTryThis(5);
// methodTryThat(6);
References
author: Ognjen Savkovic (Ognjen [DOT] Savkovic [AT] unibz [DOT] it)
Last edited: March 2015