Code Conventions for the Java Programming Language
Coding standards
Coding standards are collections of rules and guidelines that determine the programming style, procedures, and methods for a programming language.
Why Have Code Conventions
Code conventions are important to programmers for a number of reasons:
•80% of the lifetime cost of a piece of software goes to maintenance.
•Hardly any software is maintained for its whole life by the original author.
•Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
•If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.
•Write well-structured, this eases the understanding of the code for any developers who gets on the codebase.
•Without the coding conventions, every individual in a team will settle their coding styles. It will not be easy to maintain and debug the code in the near future.
Benefits of coding standards
•Easy team integration
•Increased code quality efficiency and easy for maintaining
•Reduce code complexity
•Reduce development cost
•Enables the creation of reusable code.
•Makes it easier to detect errors.
•Offers uniformity to the code created by different engineers.
Drawbacks of not having proper coding conventions for a team.
Without predefined conditions that all team member should follow can result in the following:
•Reduced engineer’s motivation
•Increased development time
•Complex codebase structure
Common Aspects of Coding Standard
o Naming Conventions: The naming convention is how your packages, classes methods, variables, etc. should be named. ( eg. camelCase, PascalCase or snake_case)
o File and folder Naming and Organization: This is how your file and folder should be named and structured
o Formatting and Indentation: The code should be written in a standardized format and indentation (In programming, indentation is just like formatting. It is used to make the code readable to other users because it makes the code easier to edit, displays how the braces match up, and shows the logic of the program in well-organized fashion)
o Commenting and Documenting: This makes it easy for the reviewer of your code to better understand codes methods and declarations
1. User proper comment explaining methods purpose,
2. Update readme file in package/application
3. Classes and Functions: This specifies how classes and functions should behave.
4. Testing: This specifies which approach and tools should be used to test the codes
All in all, it is crucial for a developers’ team to have proper coding conventions and standards to guide them during the development, this will help the team to maintain the code quality and would decrease the time spent by new developers trying to understand the complex codebase.
README File
README file must be maintained with the information of software (project, product). About software, Tech stack (framework, libraries with their versions). It can be used to summarizes the contents of a particular directory.
1. File Organization
o A file consists of sections that should be separated by blank lines and an optional comment identifying each section.
Beginning Comments
o /*
* Classname
*
* Version information
*
* Date
*
* Author
*/
Class and Interface Declaration
Class ( static) variables
First the public class variables, then the protected, then package level (no access modifier), and then the private.
Instance variables
First public, then protected, then package level (no access modifier), and then private.
Methods
These methods should be grouped by functionality rather than by scope or accessibility. For example,
a private class method can be in between two public instance methods.
The goal is to make reading and understanding the code easier.
o Files longer than 2000 lines are cumbersome and should be avoided.
2. Indentation
Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).
2.1 Line Length
o Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools.
o Note: Examples for use in documentation should have a shorter line length—generally no more than 70 characters.
2.2 Wrapping Lines
When an expression will not fit on a single line, break it according to these general principles:
o Break after a comma.
o Break before an operator.
o Prefer higher-level breaks to lower-level breaks.
o Align the new line with the beginning of the expression at the same level on the previous line.
o If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces (Tab) instead.
Here are some examples of breaking method calls:
someMethod(longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);
var = someMethod1(longExpression1,
someMethod2(longExpression2,
longExpression3));
Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
longName1 = longName2 * (longName3 + longName4 - longName5)+ 4 * longname6; // PREFER
longName1 = longName2 * (longName3 + longName4
- longName5) + 4 * longname6; // AVOID
3. Declarations
3.1 Number Per Line
One declaration per line is recommended since it encourages commenting. In other words,
int level; // indentation level
int size; // size of table
is preferred over
int level, size;
3.2 Placement
Put declarations only at the beginning of blocks.
void MyMethod() {
int int1; // beginning of method block
if (condition) {
int int2;// beginning of "if" block
...
}
}
3.3 Initialization
Try to initialize local variables where they’re declared. The only reason not to initialize a variable where it’s declared is if the initial value depends on some computation occurring first.
3.4 Limited use of global
Avoid to declare a global instance or variable if not required
4. Statements
4.1 Simple Statement
Each line should contain at most one statement. Example:
argv++; argc--; // AVOID!
4.2 Compound Statement
if (condition) {
statements;
}
Note: if statements always use braces {}. Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES {}!
statement;
5. White Space
5.1 Blank line
Blank lines improve readability by setting off sections of code that are logically related.
Two blank lines should always be used in the following circumstances:
o Between sections of a source file
o Between class and interface definitions
One blank line should always be used in the following circumstances:
o Between methods
o Between the local variables in a method and its first statement
o Before a block or single-line comment
Recommended by LinkedIn
o Between logical sections inside a method to improve readability
5.2 Blank Space
Blank spaces should be used in the following circumstances:
while (true) {
...
}
a += c + d;
a = (a + b) / (c * d);
while (d++ = s++) {
n++;
}
printSize("size is " + foo + "\n");
6. Naming Conventions
Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.
The conventions given in this section are high level.
Identifier Type
Rules for Naming
Examples
Packages
The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.
Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.
com.sun.eng
com.apple.quicktime.v2
edu.cmu.cs.bovik.cheese
Classes
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
class Raster;
class ImageSprite;
Interfaces
Interface names should be capitalized like class names.
interface RasterDelegate;
interface Storing;
Methods
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
run();
runFast();
getBackground();
Variables
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
int i;
char c;
float myWidth;
Constants
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging. 65 = A, NaN (not a number))
static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;
7. Programming Practices
7.1 Providing Access to Instance and Class Variables
Don’t make any instance or class variable public without good reason. Often, instance variables don’t need to be explicitly set or gotten—often that happens as a side effect of method calls.
7.2 Referring to Class Variables and Methods
Avoid using an object to access a class (static) variable or method. Use a class name instead. For example:
classMethod(); //OK
AClass.classMethod(); //OK
anObject.classMethod(); //AVOID!
7.2 Constants
Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values.
7.3 Parentheses
if (a == b && c == d) // AVOID!
if ((a == b) && (c == d)) // RIGHT
7.4 Returning Values
Try to make the structure of your program match the intent. Example:
if (booleanExpression) {
return TRUE;
} else {
return FALSE;
}
should instead be written as
return booleanExpression;
if (cond != null) {
return TRUE;
} else {
return FALSE;
}
should instead be written as
if (cond == null) {
return FALSE;
}
8. Usage of proper Collection
9. Performance
9.1 Database / Network calls
References
For Further Inquiries