Java Coding Best Practices

Suraj Kumar Gupta
3 min readJan 22, 2022

--

Java has been one of the most dominant programming languages from the beginning. In the current times of rapid advancements, where many programming languages that once had a strong presence in the industry are way long dead, Java is still relevant and speedily growing with the trends.

1. Using Naming Conventions

First and foremost, before writing any code you should specify a set of naming conventions for your Java project, such as how to name classes and interfaces, how to name methods, how to name variables, how to name constants, etc. These conventions must be obeyed by all programmers in your team.

Here are some general naming rules:

  • Class and interface names should be nouns, starting with an uppercase letter. For example Student, Car, Rectangle, Painter, etc.
  • Package name should be an in lowercase ASCII letter such as java, lang. If the name contains multiple words, it should be separated by dots (.) such as java.util, java. lang. For examples mypackage, com.company.application.ui, com.sun.eng, com.apple.quicktime.v2
  • Variable names should be nouns, starting with a lowercase letter. For example number, counter, birthday, gender, etc.
  • Method names should be verbs, starting with a lowercase letter. For example run, start, stop, execute, etc.
  • Constant names should have all UPPERCASE letters and words are separated by underscores. For example: MAX_SIZE, MIN_WIDTH, MIN_HEIGHT, etc.
  • Using camelCase notation for names. For example: studentManager, carController, numberOfStudents, runAnalysis, etc.

2. Ordering Class Members by Scopes

The best practice is to organize member variables of a class by their scopes from most restrictive to least restrictive. That means we should sort the members by the visibility of the access modifiers: private, default (package), protected, and public. And each group is separated by a blank line.

Example:

class Main {

public static void main(String[] args){

private String errorMessage;

private int numberOfColumns;

private int numberOfRows;

float columnWidth;

float rowHeight;

protected String[] columnNames;

protected List<Student> listStudents;

public int numberOfStudents;

public String title;

}

}

3. Class Members should be private

According to Joshua Bloch (author of Effective Java), we should minimize the accessibility of class members (fields) as inaccessible as possible. That means we should use the lowest possible access modifier (hence the private modifier) to protect the fields. This practice is recommended in order to enforce information hiding or encapsulation in software design.

Example:

class Main {

public static void main(String[] args){

private String name;

private int age;

public void setName(String name){

if (name == null || name.equals(“”)){

throw new IllegalArgumentException(“Name is invalid”);

}

this.name = name;

}

public void setAge(int age){

if (age < 1 || age > 100){

throw new IllegalArgumentException(“Age is invalid”);

}

this.age = age;

}

}

}

4. Using Underscores in Numeric Literals

This little update from Java 7 helps us write lengthy numeric literals much more readable.

public static void main(String[] args){

int maxUploadSize = 20_971_520;

long accountBalance = 1_000_000_000_000L;

float pi = 3.141_592_653_589F;

}

5. Avoid using for loops with indexes

Don’t use a for loop with an index (or counter) variable if you can replace it with the enhanced for loop (since Java 5) or forEach (since Java 8). It’s because the index variable is error-prone, as we may alter it incidentally in the loop’s body, or we may start the index from 1 instead of 0.

class Main {

public static void main(String[] args){

String[] names = {“Alice”, “Bob”, “Carol”, “David”, “Eric”, “Frank”};

for (String aName : names) {

doSomething(aName);

}

}

}

Conclusion

Nowadays many IDEs such as IntelliJ or Eclipse already provide code formating options using which most of the coding conventions can be followed. We still need to add comments as they are not yet smart enough to also do that for us! Anyway, the takeaway is that we should write code in such a way that makes the life of future authors and maintainers easy.

--

--