Tips to write Cleaner Code in Java
1. Follow Naming Conventions
Naming conventions in Java are crucial for readability and maintenance. They help other developers understand the purpose of your classes, methods, and variables quickly.
- Classes should be named using PascalCase and should be nouns. For example:
public class CustomerAccount { ... }
- Methods should be named using camelCase and should be verbs or verb phrases. For example:
public void calculateTotalPrice() { ... }
- Variables should also use camelCase. For example:
int totalPrice; String customerName;
2. Limit Line Length to 120 Characters
Long lines of code can be difficult to read and understand. Keep your lines under 120 characters to ensure they are easily readable on all screens.
For example, instead of:
String result = someService.doSomethingReallyLongAndComplicated(someParameter, anotherParameter, yetAnotherParameter);
Break it into multiple lines:
String result = someService.doSomethingReallyLongAndComplicated(
someParameter,
anotherParameter,
yetAnotherParameter
);
3. Use Java Records Instead of Getters and Setters
Java records provide a compact syntax for declaring classes that are intended to be simple data carriers. They automatically provide getters, toString()
, equals()
, and hashCode()
methods.
For example, instead of writing:
public class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
Use a record:
public record User(String name, int age) { }
4. Break Down Large Public Methods
Large methods can be difficult to understand and maintain. If a public method grows too large, break it into smaller, more manageable sub-methods.
For example, instead of this:
public void processOrder(Order order) {
// long logic to validate order
// long logic to calculate total
// long logic to update inventory
// long logic to notify customer
}
Use this:
public void processOrder(Order order) {
validateOrder(order);
calculateTotal(order);
updateInventory(order);
notifyCustomer(order);
}
Each sub-method performs a specific task, making the code easier to read and maintain.
5. Replace Constants with Enums
Using enums instead of constants improves code readability, type safety, and maintainability. Enums provide a clear and concise way to represent a fixed set of constants.
Example:
// Before using constants
public class StatusConstants {
public static final int ACTIVE = 1;
public static final int INACTIVE = 2;
public static final int PENDING = 3;
}
public class User {
private int status;
public void setStatus(int status) {
this.status = status;
}
}
// After using enums
public enum Status {
ACTIVE,
INACTIVE,
PENDING
}
public class User {
private Status status;
public void setStatus(Status status) {
this.status = status;
}
}
Replacing constants with enums enhances code quality, reduces errors, and facilitates better code maintenance.
6. Use Java Streams for Collection Operations
Java Streams provide a functional approach to handling collections and can make your code more concise and readable.
Example: We have a list of numbers and we need to find out the count of even numbers.
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Without Streams:
// calculate count of even numbers from list
int count = 0;
for (Integer number : numbers) {
if (number % 2 == 0) {
count++;
}
}
System.out.println(count); // Output: 5
With Streams:
// calculate count of even numbers from list
long count = numbers.stream()
.filter(number -> number % 2 == 0)
.count();
System.out.println(count); // Output: 5
7. Use Static Code Analysis Tools
Tools like SonarLint can help you identify code smells, bugs, and security vulnerabilities in your code. Integrate these tools into your IDE to catch issues early in the development process.
For example, SonarLint can highlight unused variables, detect potential null pointer dereferences, and suggest improvements for your code. By following these best practices, you can write cleaner, more maintainable Java code. Clean code not only makes your work easier but also helps your team and future developers who will work with your codebase.
Other tools: SonarLint, Checkstyle, PMD.