Why Clean Code Matters: Practical Tips for Naming, Classes, Functions & Tests
This comprehensive guide explains why clean code is crucial for productivity and company health, and provides actionable advice on writing clean code through proper naming, class design, function structuring, and testing practices, illustrated with Java examples and refactoring patterns.
Through this article you will understand the importance of clean code for projects, companies, and yourself, and learn how to write clean code.
1. Why keep code clean?
Messy code grows over time, reducing productivity and leading to problems such as difficult extensibility, program crashes, overtime, increased company costs, and even company failure.
Code is hard to extend or extensions cause other issues
Program crashes
Overtime
Increased company cost (hiring)
Potential company bankruptcy
1.1 Start clean from the beginning
Write clean code from the start; if you encounter messy code, refactor it immediately. Never adopt a "later" mindset.
later equal never1.2 How to write clean code?
Clean code should be highly readable, avoid duplication, and follow design pattern principles such as SOLID:
High readability – code should read like prose
Avoid duplicate code
Follow design pattern principles
Single Responsibility
Open/Closed Principle
Liskov Substitution
Dependency Inversion
Interface Segregation
Demeter’s Law
Composition over inheritance
2. Naming
Good naming improves readability, reduces understanding cost, and boosts efficiency.
2.1 Bad naming examples
public interface Animal {
void abc();
}The method name abc gives no indication of its purpose.
public interface Animal {
void cry();
}Renaming to cry makes the intent clear.
Inconsistent naming, redundant words, and unclear prefixes should be avoided. Use conventions like getXxx() for single objects and listXxx() for collections.
// Get a single object
getXxx();
// Get multiple objects
listXxx();3. Classes
Clean classes should satisfy:
Single Responsibility
Open/Closed Principle
High cohesion
3.1 Single Responsibility
Classes should be small and have only one reason to change, which reduces complexity, improves readability, maintainability, and lowers change risk.
3.2 Open/Closed Principle
Software should be open for extension but closed for modification. Refactor large classes into smaller, specialized ones.
public abstract class Sql {
public abstract void insert();
public abstract void countInsert();
}After refactoring, separate responsibilities into distinct classes.
public abstract class CountSql {
public abstract void countInsert();
}3.3 Cohesion
High cohesion means methods operate on the same set of variables, forming a logical whole. Low cohesion should be addressed by splitting the class.
4. Functions
Clean functions should:
Do one thing
Have good naming
Have clean parameters
Consider return values carefully
4.1 Do one thing
Break large functions into smaller ones, each handling a single responsibility.
public String upload() {
// validate image (pseudo 80 lines)
// compress image (pseudo 50 lines)
// return status (pseudo 5 lines)
return "0";
} public String upload() {
check(); // validate image
compress(); // compress image
return "0"; // return status
}4.2 Function naming
Names should be descriptive. Avoid ambiguous names like addCharacter when the operation (append, insert) is unclear.
public String appendCharacter(String originString, char ch);
public String insertCharacter(String originString, char ch, int insertPosition);4.3 Parameters
Keep parameters minimal; encapsulate when exceeding three. Avoid Boolean flags and output parameters.
public List<Student> findStudent(int age, String name, String country, int gender);
// Refactored
public List<Student> findStudent(Student student); // Bad: Boolean flag
render(Boolean isSuite);
// Refactored
renderForSuite();
renderForSingleTest(); // Bad: Output parameter
public void findStudent(); // modifies passed object
// Refactored
student.doSomething();4.4 Return values
Separate commands from queries; use exceptions instead of error codes.
public void addElement(Element element);
public Boolean isAdd(Element element); try {
tryToShutDown();
} catch (DeviceShutDownError e) {
logger.log(e);
}4.5 Writing such functions
Start with functional code, then refactor immediately; remember “later equal never”.
4.6 Code quality tools
Tools like SonarLint help detect issues such as duplicate code, potential NPEs, and suggest fixes, enabling quantifiable metrics like bug rate and duplication rate.
5. Testing
Clean test code is essential for verifying functionality.
5.1 TDD
Test‑Driven Development is a core agile practice that drives design and reduces bugs.
5.2 FIRST principles
Tests should be Fast, Independent, Repeatable, Self‑validating, and Timely.
5.3 Given‑When‑Then pattern
Structure tests as given (setup), when (action), then (assertion) to improve 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 Auto‑generated tests
IDEA plugins such as Squaretest (paid) and TestMe (free) can generate test skeletons.
6. Conclusion
Writing clean code improves readability, extensibility, development efficiency, reduces overtime, and raises your professional level. Every developer should read Clean Code to enhance coding ability and mindset, and strive to write clean code from the start rather than relying on later fixes.
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.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
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.
