Best Coding Practices in Java

Srikanth Dannarapu
Javarevisited
Published in
4 min readMar 2, 2023
  1. Use descriptive and meaningful names for variables, methods, and classes.

Good Example:

public class Car {
private String model;
private int year;

public Car(String model, int year) {
this.model = model;
this.year = year;
}

public void startEngine() {
System.out.println("Starting " + model + " engine");
}
}

Bad Example:

public class C {
private String a;
private int b;

public C(String a, int b) {
this.a = a;
this.b = b;
}

public void s() {
System.out.println("Starting " + a + " engine");
}
}

2. Follow the Single Responsibility Principle (SRP) and keep methods and classes focused on a single task.

Good Example:

public class Calculator {
public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {
return a - b;
}
}

Bad Example:

public class Calculator {
public static int addAndMultiply(int a, int b, int c) {
return (a + b) * c;
}

public static int subtractAndDivide(int a, int b, int c) {
return (a - b) / c;
}
}

3. Avoid using magic numbers in your code and use constants or enums instead.

Good Example:

public class Circle {
private static final double PI = 3.14;
private double radius;

public Circle(double radius) {
this.radius = radius;
}

public double getArea() {
return PI * radius * radius;
}
}

Bad Example:

public class Circle {
private double radius;

public Circle(double radius) {
this.radius = radius;
}

public double getArea() {
return 3.14 * radius * radius;
}
}

4. Use the try-with-resources statement when working with resources that implement the AutoCloseable interface.

Good Example:

try (FileInputStream fis = new FileInputStream("file.txt")) {
// Do something with the input stream
} catch (IOException e) {
// Handle the exception
}

Bad Example:

FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
// Do something with the input stream
} catch (IOException e) {
// Handle the exception
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Handle the exception
}
}
}

5. Use the StringBuilder class when constructing strings in a loop or when concatenating multiple strings.

Good Example:

String message = "Hello, ";
String name = "John";
StringBuilder sb = new StringBuilder();
sb.append(message);
sb.append(name);
String greeting = sb.toString();

Bad Example:

String message = "Hello, ";
String name = "John";
String greeting = message + name;

6. Use interfaces to define contracts and provide abstraction.

Good Example:

public interface Vehicle {
void startEngine();
void stopEngine();
void accelerate(int speed);
void brake();
}

public class Car implements Vehicle {
// Implementation of the methods defined in the Vehicle interface
// ...
}

Bad Example:

public class Car {
public void startEngine() {
// ...
}

public void stopEngine() {
// ...
}

public void accelerate(int speed) {
// ...
}

public void brake() {
// ...
}
}

7. Use meaningful and consistent indentation to make your code easier to read

Good Example:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Bad Example:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

8. Use the @Override annotation when overriding a method to help detect errors.

Good Example:

public class Vehicle {
public void startEngine() {
// ...
}
}

public class Car extends Vehicle {
@Override
public void startEngine() {
// ...
}
}

Bad Example:

public class Vehicle {
public void startEngine() {
// ...
}
}

public class Car extends Vehicle {
public void startEngine() {
// ...
}
}

9. Use meaningful and consistent exception handling to handle errors gracefully.

Good Example:

try {
// Some code that may throw an exception
} catch (IOException e) {
logger.error("An error occurred while reading the file", e);
// Handle the exception gracefully
} catch (SQLException e) {
logger.error("An error occurred while executing the SQL query", e);
// Handle the exception gracefully
} catch (Exception e) {
logger.error("An unexpected error occurred", e);
// Handle the exception gracefully
}

Bad Example:

try {
// Some code that may throw an exception
} catch (Exception e) {
// Ignore the exception or print a generic message
e.printStackTrace();
}

10. Use the Java coding conventions to make your code consistent and easier to read.

Good Example:

public class Calculator {
public static final int MAX_OPERANDS = 2;

private int result;

public Calculator() {
result = 0;
}

public int add(int... operands) {
if (operands.length > MAX_OPERANDS) {
throw new IllegalArgumentException("Too many operands");
}
for (int operand : operands) {
result += operand;
}
return result;
}
}

Bad Example:

public class calculator {
public static final int MAX_OPERANDS = 2;

private int result;

public calculator() {
result = 0;
}

public int add(int[] operands) {
if (operands.length > MAX_OPERANDS) {
throw new IllegalArgumentException("Too many operands");
}
int sum = 0;
for (int i = 0; i < operands.length; i++) {
sum += operands[i];
}
result = sum;
return result;
}
}

11. Use static methods sparingly

Static methods can be useful in certain cases, but they can also make code harder to test and maintain. Avoid using static methods for things that change frequently, and consider using dependency injection instead.

public class StringUtils {
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
}

public class User {
private String name;

public boolean isNameNullOrEmpty() {
return StringUtils.isNullOrEmpty(name);
}
}

In this example, the StringUtils class has a static method that checks if a string is null or empty. However, this method could be made an instance method of the User class, making the code more testable and maintainable.

Thanks, before you go:

  • 👏 Please clap for the story and follow the author 👉
  • Please share your questions or insights in the comments section below. Let’s help each other and become better Java developers.
  • Let’s connect on LinkedIn

--

--