12 Simple Clean Code Tips
Clean code is the foundation of maintainable and scalable software. Here are 12 simple tips to help you write clean code in Java, along with detailed explanations and examples of what to avoid and what to do instead.
1. Use Meaningful Variable Names
Using meaningful variable names makes your code more readable and understandable. Names should describe the purpose of the variable.
**Wrong:**
int d; // number of days
This variable name is too short and doesn’t convey its purpose.
**Correct:**
int numberOfDays;
The variable name numberOfDays
clearly describes its purpose.
2. Avoid Magic Numbers
Magic numbers are numeric literals that are used directly in the code without explanation. Instead, use constants with meaningful names.
**Wrong:**
double circumference = radius * 3.14159;
The value 3.14159
is a magic number. It's not clear what this value represents.
**Correct:**
final double PI = 3.14159;
double circumference = radius * PI;
By using a named constant PI
, the code becomes more readable and maintainable.
3. Limit the Length of Functions
Long functions with multiple responsibilities are hard to read, understand, and maintain. Break them down into smaller, single-responsibility functions.
*Wrong:**
public void processOrder() {
// validate order
if (order.isValid()) {
// process payment
if (paymentService.process(order.getPayment())) {
// ship order
shippingService.ship(order);
}
}
}
This function needs to do more things: validating the order, processing payment, and shipping the order.
*Correct:**
public void processOrder() {
if (validateOrder() && processPayment()) {
shipOrder();
}
}
private boolean validateOrder() {
// validate order
return order.isValid();
}
private boolean processPayment() {
// process payment
return paymentService.process(order.getPayment());
}
private void shipOrder() {
// ship order
shippingService.ship(order);
}
Each function has a single responsibility, making the code easier to read and maintain.
4. Use Descriptive Method Names
Method names should clearly describe what the method does. Avoid vague names.
**Wrong:**
public void calc() {
// code
}
The method name calc
is vague and needs to describe what the method calculates.
**Correct:**
public void calculateTotalPrice() {
// code
}
The method name calculateTotalPrice
clearly describes its purpose.
5. Prefer Immutable Objects
Immutable objects are simpler, safer, and easier to reason about. Use `final` fields and don’t provide setters.
**Wrong:**
public class User {
public String name;
public int age;
}
This class allows direct modification of its fields, making it mutable.
**Correct:**
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;
}
}
This class is immutable. Once an instance is created, its state cannot be changed.
6. Use Proper Indentation
Consistent indentation improves the readability of your code.
**Wrong:**
public class Example {
public void sampleMethod() {
if (condition) {
doSomething();
}else {
doSomethingElse();
}
}
}
Inconsistent indentation makes the code hard to read.
**Correct:**
public class Example {
public void sampleMethod() {
if (condition) {
doSomething();
} else {
doSomethingElse();
}
}
}
Proper indentation makes the code easier to read and understand.
7. Avoid Deep Nesting
Deeply nested code is hard to read and maintain. Use guard clauses to reduce nesting.
**Wrong:**
if (condition1) {
if (condition2) {
if (condition3) {
// code
}
}
}
Deep nesting makes the code hard to read.
**Correct:**
if (!condition1) return;
if (!condition2) return;
if (!condition3) return;
// code
Using guard clauses reduces nesting and improves readability.
8. Use Comments Sparingly
Comments should explain why something is done, not what is done. The code should be self-explanatory.
**Wrong:**
// This method adds two numbers
public int add(int a, int b) {
return a + b;
}
The comment is redundant because the method name and parameters are self-explanatory.
**Correct:**
public int add(int a, int b) {
return a + b;
}
Remove unnecessary comments. If you need comments, use them to explain why something is done.
9. Keep Classes Small and Focused
A class should have a single responsibility. Split large classes into smaller, focused ones.
**Wrong:**
public class UserManager {
public void addUser() { ... }
public void removeUser() { ... }
public void updateUser() { ... }
public void getUser() { ... }
public void getAllUsers() { ... }
public void validateUser() { ... }
}
This class has too many responsibilities.
**Correct:**
public class UserManager {
public void addUser() { ... }
public void removeUser() { ... }
public void updateUser() { ... }
public void getUser() { ... }
}
public class UserValidator {
public void validateUser() { ... }
}
Each class now has a single responsibility.
10. Handle Exceptions Properly
Catch specific exceptions and handle them appropriately. Avoid catching generic exceptions.
**Wrong:**
try {
// code
} catch (Exception e) {
e.printStackTrace();
}
Catching generic exceptions makes it hard to know what kind of error occurred and how to handle it.
**Correct:**
try {
// code
} catch (IOException e) {
logger.error("IO error occurred", e);
} catch (SQLException e) {
logger.error("SQL error occurred", e);
}
Catching specific exceptions makes the code more robust and easier to debug.
11. Use Enums Instead of Constants
Enums provide a better way to define a set of related constants.
**Wrong:**
public class Status {
public static final int ACTIVE = 1;
public static final int INACTIVE = 0;
}
Using constants like this can lead to errors and is less readable.
**Correct:**
public enum Status {
ACTIVE,
INACTIVE;
}
Enums are more readable and provide type safety.
12. Avoid Redundant Code
Avoid redundant code to keep your codebase clean and efficient.
**Wrong:**
if (isTrue == true) {
// code
}
The comparison isTrue == true
is redundant.
**Correct:**
if (isTrue) {
// code
}
The condition if (isTrue)
is clear and concise.
Following these tips will help you write cleaner, more readable, and maintainable code in Java.
******************************** Happy coding! ***************************