Coding Guidelines in Java
Last Updated :
24 Jan, 2022
Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner.
In this article, let us understand a few coding guidelines that help to increase the readability of the program.
Why Coding Guidelines?
The coding guidelines are important because most of the software cost goes towards maintenance. And also, the software is not always developed by a single developer. Therefore, maintaining a convention for writing software increases the readability of the program.
A few of the guidelines are:
1. Naming Conventions: We generally follow the camel case convention in java programming. It means that all the classes and interfaces should be nouns, in mixed cases with the first letter of each internal word capitalized. All the methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized. The variables should be meaningful and one character variable names must be avoided. A constant variable is defined in the capital case.
2. Curly Braces: Curly braces are used to define the bodies of classes, methods, and loops. There are two standard formats for the usage of curly braces, either of which is used.
- No blank lines should be present after the opening brace or before the closing brace.
- A curly brace is applied at the end of the line that starts the class, method, loop, etc., and the closing brace is on a line by itself, lined up vertically with the start of the first line. For example:
class Geeksforgeeks {
... Geeksforgeeks(){
// Constructor
...
}
int Geek(int a, float b){
... for (int i = 0; i < Field; i++){
....
}
}
}
- Each curly brace is added on a new line, and the pair is aligned vertically. The preceding code snippet in this format would be as follows:
class Geeksforgeeks
{
... Geeksforgeeks()
{ // Constructor
...
}
int Geek(int a, float b)
{
... for (int i = 0; i < Field; i++)
{
....
}...;
}
}
3. Indentation: The unit of indentation should be 4 spaces. Tab-stops should be set exactly every 8 spaces. All indentation must be achieved by the space character and tab characters must not exist in the resultant source file. The recognized standard for increasing readability of each line is:
- Apply indentation to alike items in a vertical list (such as end-of-line comments, and identifiers in declarations).
- Surround the binary operators (including assignment) by spaces.
- Follow a semicolon or comma by a space.
- Add a space between a keyword("if", "while", "return", "catch", "switch", "for") and a succeeding parenthesis.
- Surplus parentheses can also help to highlight the structure of expressions (but avoid using too many nested parentheses).
- Insert blank lines to differentiate between the important parts of the code.
- Let's implement all the above guidelines in a code:
class Geeksforgeeks {
private int s;
private double d;
Geeksforgeeks()
{ // Constructor
s = 1;
d = 3.14;
}
int Geek(int a, float b)
{
// Must initialize local variables
int l = 0;
float le = 1;
int n = 10;
l = n - 2;
le = l + b * 3;
for (int i = 0; i & lt; n; i++) {
l = l * 2;
l = l - n;
}
return l + a;
}
}
4. White Space: White spaces also play a major part in readability as follows:
- Operators should be surrounded by a space character. For example:
The operation should be written as:
a = (b + c) * d;
And not as:
a=(b+c)*d
The loop must be initialized as:
while (true) {...}
And not as:
while(true){...}
- Commas should be followed by white space. For example:
The functions must be initialized as:
fun(a, b, c, d);
And not as:
fun(a, b, c, d);
- Colons should be surrounded by white space. For example:
The case statements must be initialized as:
case 100 : break;
And not as:
case 100:break;
- Semicolons in for statements should be followed by a space character. For example:
The for loop must be initialized as:
for (i = 0; i < n; i++)
And not as:
for(i=0;i<n;i++)
5. Comments: Java programs can have two types of comments. They are Implementation and Documentation. Comments should contain only the information that is relevant for reading and understanding the program. For example, information about how the package is built or in what directory it resides should not be included in the program as a comment.
- Implementation Comments: Implementation comments are delimited by //. Java also allows the use of /*...*/ for implementation comments. Implementation comments are used for notes about a particular implementation or for temporarily removing code. Programs can have four styles of implementation comments: block, single-line, trailing, and temporarily removing code.
- Block comments are used to provide descriptions of files, methods, data structures, and algorithms. Block comments may be used at the beginning of each file and before each method or within methods. Block comments inside a method should be indented to the same level as the code they describe. A block comment should have a blank line before its start unless it comes immediately after the start of a compound statement. For example:
// block comment on line 1
// block comment on line 2
// block comment on line 3
- Single-line comments can appear on a single line indented to the level of the code that follows. If a comment can not be written in a single line, it should follow the block comment format. A single-line comment should be preceded by a blank line unless it comes immediately after the start of a compound statement. For example:
a = 10;
b = 20;
// a single-line comment
c = a * b;
- Trailing(very short) comments can appear on the same line of the code they describe but should be separated from the code at a far off distance. If more than one short comment appears in a section of related code, they should all be indented to the same tab setting. For example:
if (a == 2) {
b = true; // special case
}
else {
c = isPrime(x); // works only for odd
}
- Temporarily removing code: The // delimiter can comment out a partial or a complete line. It can also be used in multiple lines to comment out entire sections of code. It is important to note that this should only be used temporarily while the code is in active development; the unused code should eventually be physically removed as it can make the source more difficult to maintain. For example:
if (a > 1) {
b = a; // + 1;
...
}
else {
// b = 2;
...
}
- Documentation Comments: Documentation comments describe Java classes, interfaces, constructors, methods, and fields. They are delimited by /**…*/. Note the double-asterisk (**) at the beginning with one comment per class, interface, or member. This comment should appear just before the declaration with no space between the comment and the code it refers to. Documentation comments can be extracted to HTML files using the javadoc tool. Javadoc of class members can be specified on a single line as follows:
/** This is a java documentation comment */
private int comments_;
Documentation comments are meant to describe the specification of the code, from an implementation-free perspective, to be read by developers who might not necessarily have the source code at hand. Java associates documentation comments with the first declaration after the comment. As a result, documentation comments should not be present inside a method or constructor definition block. For example:
Though we can say that the above-mentioned guidelines are not definitive and they are relative, but it is always preferred to maintain the guidelines because the software is never developed by a single person and might not be maintained by the same team who has developed the software. In order to solve any bugs in the software, the deployed code must be easily readable. Following the above guidelines makes the code readable not only for the developer but also for a new person who is reading the code for the first time.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read