Why Clean Code Matters: Master Naming, Classes, and Functions for Better Software
This article explains why clean code is essential for project success and company health, outlines the consequences of messy code, and provides practical guidelines on naming, class design, function design, testing, and using tools like SonarLint to write maintainable, high‑quality software.
Why Keep Code Clean?
Unclean code becomes harder to maintain over time, reducing productivity and leading to problems such as difficult extensions, crashes, overtime, increased hiring costs, and even company failure.
1. Start Clean and Stay Clean
Write clean code from the beginning; if you spot unclean code, refactor it immediately—never postpone with a "later" mindset.
later equal never1.2 How to Write Clean Code
High readability – code should read like prose.
No duplicate code.
Follow design‑pattern principles (SOLID):
Single Responsibility
Open‑Closed
Liskov Substitution
Dependency Inversion
Interface Segregation
Law of Demeter
Composite Reuse Principle
2. Naming
Good names improve readability, lower understanding cost, and reduce overtime.
2.1 Bad Naming Example
public interface Animal {
void abc();
}The method name abc gives no clue about its purpose.
2.2 Good Naming Example
public interface Animal {
void cry();
}Now the purpose is obvious.
Other naming pitfalls:
Inconsistent naming (e.g., findOneById vs queryAllStudent).
Redundant words (e.g., adding Variable or Table unnecessarily).
public interface StudentRepository extends JpaRepository<AlertAll, String> {
Student findOneById(@Param("id") String id);
List<Student> findAll();
}3. Classes
Clean classes should satisfy:
Single Responsibility
Open‑Closed
High Cohesion
3.1 Single Responsibility
Classes should be small and have only one reason to change, which improves readability, maintainability, and reduces risk.
public abstract class Sql {
// operate SQL
public abstract void insert();
// count inserts
public abstract void countInsert();
}Refactor the counting responsibility into a separate class:
public abstract class CountSql {
public abstract void countInsert();
}3.2 Open‑Closed Principle
Software should be closed for modification but open for extension. Instead of adding new methods to Sql, create subclasses.
public abstract class Sql {
public abstract void generate();
}
public class CreateSql extends Sql {
@Override
public void generate() { /* implementation */ }
}
public class UpdateSql extends Sql {
@Override
public void generate() { /* implementation */ }
}3.3 Cohesion
High cohesion means a class’s methods and variables work together toward a single purpose.
4. Functions
Guidelines for clean functions:
Do one thing only.
Use descriptive names.
Keep parameters minimal.
Handle return values properly.
4.1 Do One Thing
Original upload method mixed validation, compression, and result handling (≈135 lines). Refactor into separate steps:
public String upload() {
check();
compress();
return "0";
}4.2 Function Naming
Bad example:
public String addCharacter(String originString, char ch);Good examples:
public String appendCharacter(String originString, char ch);
public String insertCharacter(String originString, char ch, int position);4.3 Parameters
Prefer fewer parameters; encapsulate related data into objects; avoid boolean flags and output parameters.
public List<Student> findStudent(Student student);
// instead of many primitive parameters4.4 Return Values
Separate command and query; use exceptions instead of error codes.
public void addElement(Element element);
public Boolean isAdd(Element element);4.5 Refactoring Mindset
Write functional code first, then immediately refactor. Remember: later equal never.
4.6 Code Quality Tools
Tools like SonarLint can detect duplicate code, potential null‑pointer exceptions, and other issues, helping quantify bug rates and code quality.
5. Testing
Testing validates code correctness and should also be clean.
5.1 Test‑Driven Development (TDD)
TDD drives design by writing failing tests before production code.
5.2 FIRST Principles
Fast
Independent
Repeatable
Self‑validating
Timely
5.3 Given‑When‑Then Pattern
@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
IDEA plugins such as Squaretest (paid) and TestMe (free) can generate unit tests automatically.
6. Conclusion
Writing clean code improves readability, extensibility, development efficiency, reduces overtime, and raises a developer’s skill level. Everyone should read "Clean Code" to enhance coding ability and mindset, and write clean code proactively rather than fixing it later.
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.
