Master Clean Code: 6 Proven Strategies to Boost Java Quality and Productivity
This article explains why clean code is essential for Java projects, covering naming conventions, class design, function responsibilities, testing practices, and tools, and provides concrete examples and refactorings to improve readability, maintainability, and team efficiency.
1. Why Keep Code Clean?
Unclean code accumulates over time, lowering productivity and leading to problems such as poor extensibility, crashes, overtime, higher costs, and even company failure.
Code becomes hard to extend and changes cause side effects
Program crashes
Overtime work
Increased hiring costs or possible shutdown
1.1 Start Clean from the Beginning
Write clean code from the start and refactor immediately; never postpone.
later equal never2. Naming
2.1 Bad Naming
Example of a meaningless method name:
public interface Animal {
void abc();
}Better naming:
public interface Animal {
void cry();
}2.2 Naming Consistency
Inconsistent method names cause confusion. Example before:
public interface StudentRepository extends JpaRepository<AlertAll, String> {
Student findOneById(@Param("id") String id);
List<Student> queryAllStudent();
}After standardising:
public interface StudentRepository extends JpaRepository<AlertAll, String> {
Student findOneById(@Param("id") String id);
List<Student> findAll();
}2.3 Redundant Naming
Avoid unnecessary words in names, e.g., using prefixes:
// Get a single object
getXxx();
// Get multiple objects
listXxx();3. Classes
Clean classes should follow single responsibility, open‑closed principle, and high cohesion.
3.1 Single Responsibility
A class should have only one reason to change. Large classes usually violate this.
Reduce complexity
Improve readability
Enhance maintainability
Lower change risk
Example of a class with two responsibilities:
public abstract class Sql {
// SQL operation
public abstract void insert();
// Statistics
public abstract void countInsert();
}Refactored into separate classes:
public abstract class CountSql {
public abstract void countInsert();
}3.2 Open‑Closed Principle
Modules should be closed for modification but open for extension. Adding new logic without changing existing code reduces bugs.
Violating example:
public abstract class Sql {
public abstract void insert();
public abstract void update();
public abstract void delete();
}After refactoring using inheritance:
public abstract class Sql {
public abstract void generate();
}
public class CreateSql extends Sql {
@Override
public void generate() { /* ... */ }
}
public class UpdateSql extends Sql {
@Override
public void generate() { /* ... */ }
}3.3 Cohesion
High cohesion means methods share the same data; a class with many unrelated fields has low cohesion.
4. Functions
4.1 Do One Thing
Functions should be short and focused. Example of a long method handling validation, compression, and result:
public class PicService {
public String upload() {
// validation (80 lines)
// compression (50 lines)
// return status (5 lines)
return "0";
}
}Refactored version:
public String upload() {
check();
compress();
return "0";
}4.2 Function Naming
Names should be descriptive. Bad example:
public String addCharacter(String originString, char ch);Better examples:
// Append to the end
public String appendCharacter(String originString, char ch);
// Insert at a position
public String insertCharacter(String originString, char ch, int insertPosition);4.3 Parameters
Prefer few parameters; encapsulate when exceeding three.
public List<Student> findStudent(int age, String name, String country, int gender);
// Encapsulated
public List<Student> findStudent(Student student);Avoid boolean flags that create two code paths:
// Bad
render(Boolean isSuite);
// Good
renderForSuite();
renderForSingleTest();4.4 Return Values
Separate commands from queries. Instead of returning a boolean from an add method, split:
public void addElement(Element element);
public Boolean isAdd(Element element);Prefer exceptions over error codes.
5. Tests
5.1 Test‑Driven Development (TDD)
TDD writes a failing test before production code, ensuring code meets requirements from the start.
5.2 FIRST Principles
Fast
Independent
Repeatable
Self‑validating
Timely
5.3 Given‑When‑Then Pattern
Structure tests into three phases for readability.
@Test
public void shouldReturnItemNameInUpperCase() {
// Given
Item mockedItem = new Item("it1", "Item 1", "This is item 1", 2000, true);
when(itemRepository.findById("it1")).thenReturn(mockedItem);
// When
String result = itemService.getItemNameUpperCase("it1");
// Then
verify(itemRepository, times(1)).findById("it1");
assertThat(result, is("ITEM 1"));
}5.4 Automated Test Generation
IDE plugins such as Squaretest (paid) and TestMe (free) can generate unit tests automatically.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
