Java Coding Standards
As humans we have to communicate with each other, we use a language to communicate with each other.And we use a language to communicate with the computer , for the we use many languages like Java,C,Kotlin and many more. We can’t work on a single project the whole life or solo to build a good project you need a team to help the fellow programmers to make your code easily readable you need to follow some coding standards , we are not apes we are well civilised so we follow some standards of communication.
In this blog , I will mention some Java coding standards to write a clean code.
Naming :
- Names representing packages should be in all lower case.
om.company.application.ui2.Class/enum names must be nouns and written in PascalCase.
Line, AudioSystem3.Variable names must be in camelCase.
line, audioSystem4.Constant names must be all uppercase using underscore to separate words (aka SCREAMING_SNAKE_CASE).
MAX_ITERATIONS, COLOR_RED 5.Names representing methods must be verbs and written in camelCase.
getName(), computeTotalWidth(), fetchName()Note : ‘_’ underscore can be used in test cases for good differentiations.
6.Boolean variables/methods should be named to sound like booleans.
//variables
isSet, isVisible, isFinished, isFound, isOpen, hasData, wasOpen
//methods
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;7. Plural form should be used on names representing a collection of objects.
Collection<Point> points;
int[] values;Layout :
- Basic indentation should be 4 spaces (not tabs).
for (i = 0; i < nElements; i++) {
a[i] = 0;
}Note : Use auto line formatter for this 😁
2. Line length should be no longer than 120 chars.
There will be a line defining the limit our code should not cross that to ensure easily readability. The reason to use the hard code strings like file paths is also related to this because the api’s exceeds more than 120 character if it exceeds , they user have to explicitly scroll horizantally to read the code.
3.Place line break to improve readability
When wrapping lines, the main objective is to improve readability. Do not always accept the auto-formatting suggested by the IDE.
In general:
- Break after a comma.
- Break before an operator. This also applies to the following “operator-like” symbols: the dot separator
., the ampersand in type bounds<T extends Foo & Bar>, and the pipe in catch blockscatch (FooException | BarException e)
totalSum = a + b + c
+ d + e;
setText("Long line split"
+ "into two parts.");
method(param1,
object.method()
.method2(),
param3);4.Use K&R style brackets (aka Egyptian style).
//Good Code
while (!done) {
doSomething();
done = moreToDo();
}
//Bad Code
while (!done)
{
doSomething();
done = moreToDo();
}Note : This applies to loops, conditions, try catch and many more.
Get Nivaskodavaty’s stories in your inbox
Join Medium for free to get updates from this writer.
5.Logical units within a block should be separated by one blank line.
// Create a new identity matrix
Matrix4x4 matrix = new Matrix4x4();
// Precompute angles for efficiency
double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);
// Specify matrix as a rotation transformation
matrix.setElement(1, 1, cosAngle);
matrix.setElement(1, 2, sinAngle);
matrix.setElement(2, 1, -sinAngle);
matrix.setElement(2, 2, cosAngle);
// Apply rotation
transformation.multiply(matrix);Statements :
- The ordering of import statements must be consistent.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.loadui.testfx.GuiTest;
import org.testfx.api.FxToolkit;
import com.google.common.io.Files;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import junit.framework.AssertionFailedError;2. Imported classes should always be listed explicitly.
//Good way
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
//Bad Way
import java.util.*;3.Array specifiers must be attached to the type not the variable.
//good way
int[] a = new int[20];
//bad way
int a[] = new int[20];4. Variables should be initialised where they are declared and they should be declared in the smallest scope possible.
//Good way
int sum = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
sum += i * j;
}
}
//Bad way
int i, j, sum;
sum = 0;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
sum += i * j;
}
}These are the most important Java coding standards that have to know to write a code.
Custom Exceptions :
What is the use of custom exceptions?
There are many Usages of custom exceptions , I will explain how we use the custom exceptions for java coding standards .
Lets say you have to Withdraw the amount from your bank account.There will be three scenarios.
- The transaction is successful.
- There is no sufficient balance in you account.
- Your bank account is blocked so you can’t make any transactions.
CASE 1:
Lets consider the first case where the transaction is successful , I will throw an exception called successfulTransactionException.When we catch this in the try block we can decide that its successful.
CASE 2:
In the second scenario lets say you don’t have sufficient balance then I will throw an exception called InsuffucientBalanceException, so when we catch this exception ,I will say the user that he doesn’t have sufficient balance in his account.
CASE 3:
In the worst case if your account is blocked , I will throw an exception like FrozenAccountException.To convey the situation and occurrence of the exception.
I can throw some random exception or use the default exceptions but when another programmer try to implement my code its hard to understand what the code is doing So to make it easier to the programmers we name the exceptions.
Should we follow the java coding standards ?
Even after going through all that if you have this question , then reconsider your intellectuality(Just kidding). We have to follow coding standards its good for our readability also when developing a major project there will be a lot of classes, variables so can keep tracing everything back.So you should follow these standards to ensure code readability.
Reference:
https://se-education.org/guides/conventions/java/intermediate.html











