Coding Standards in Java
Why should we have code conventions?
Programmers value code conventions for many reasons:
- Code conventions make the software more readable, allowing engineers to understand new code more easily and quickly.
- The original author of software hardly ever maintains it for the rest of its life.
- If we are going to sell our source code as a product, make sure it’s as well packaged and clean as any other item you make.
These are a set of guidelines to follow when naming identifiers such as classes, packages, variables, constants, methods, and so on. The readability of a Java programme is important so that less time is spent analysing what the code does.
- Package: It should start with a lowercase letter. If the name contains multiple words, a dot should be used to separate them. Example: com.akshay.controller
- Classes: Class names should be nouns, written in mixed case with the first letter of each internal word capitalised, and should be short and descriptive. Example: class Employee
- Interface: Interface names should be capitalized like class names. Example: interface Coach
- Method: It should begin with a lowercase letter, and if the name contains multiple words, it should begin with a lowercase letter, then an uppercase letter. Example: saveRequest().
- Variable: It should not begin with the special characters and if the name has more than one word, begin with a lowercase letter and then an uppercase letter. Variable names should be informative. Example: String fullName.
- Constant: It should be in the uppercase letter and separated by an underscore. Example: String CONNECTION_URL.
2. Comments: Comments should be used to provide code overviews and additional information not readily available in the code itself. Only information is relevant to reading and understanding the programme should be included in the comments.
- Multi-line comment: At the start of each file and in places where code needs to be explained, block comments should be used. To set it apart from the rest of the code, it should be preceded by a blank line.
- Single line comment: Short comments can be written on a single line that is indented to the level of the following code.
// single-line comment
- Documentation comment: This type of comment is commonly used when writing code for a project/software package because it enables the generation of a documentation page for reference, which can be used to learn about the methods present, their parameters, and so on.
3. Declaration: There should be only one declaration per line.
int totalRunis preferred over int matchId, bowl, totalRun
4. Indentation: After a comma, there must be a space between two function arguments. All braces should begin on a new line, and the code following the braces should begin on a new line as well. Each block in the programme should have a proper indentation at the beginning and end.