How to Write Clean and Maintainable Code: Naming, Classes, Functions, and Testing
This article explains why clean code is essential for productivity and team collaboration, and provides practical guidelines on naming, class design, function design, and testing—including principles like single responsibility, SOLID, meaningful naming, minimal parameters, and test‑driven development—to help developers produce readable, extensible, and reliable software.
1. Why Keep Code Clean?
Untidy code reduces productivity over time, leading to hard‑to‑extend code, crashes, overtime, and increased costs.
Hard to extend or extensions cause new issues
Program crashes
Overtime
Higher company costs, even possible failure
1.1 Start Clean from the Beginning
Write clean code from the start and refactor any messy parts immediately; never postpone improvements.
later equal never1.2 How to Write Clean Code?
Clean code should be highly readable, avoid duplication, and follow design‑pattern principles such as the SOLID rules (Single Responsibility, Open‑Closed, Liskov Substitution, Dependency Inversion, Interface Segregation, Law of Demeter, Composition over Inheritance).
2. Naming
Good names improve readability and reduce understanding cost.
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();
}Method cry clearly indicates its intent.
Avoid redundant words and keep naming consistent; e.g., replace queryAllStudent with findAll for uniformity.
// get prefix for single object
getXxx();
// list prefix for multiple objects
listXxx();3. Classes
Clean classes should satisfy Single Responsibility, Open‑Closed, and high cohesion.
3.1 Single Responsibility
Each class should have only one reason to change, reducing complexity and improving maintainability.
3.2 Open‑Closed Principle
Classes should be open for extension but closed for modification; achieve this by extracting new responsibilities into separate subclasses.
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 a class’s methods operate on the same set of data, making the class easier to understand and modify.
4. Functions
Functions should do one thing, have meaningful names, clean parameters, no side effects, and clear return values.
4.1 Do One Thing
public String upload() {
// validate image
check();
// compress image
compress();
return "0"; // success flag
}4.2 Naming Functions
Prefer descriptive names like appendCharacter or insertCharacter over vague ones such as addCharacter .
4.3 Parameters
Keep parameters minimal; encapsulate multiple parameters into a domain object when they exceed three.
public List
findStudent(Student student);4.4 Return Values
Separate commands from queries and use exceptions instead of error codes.
public void addElement(Element e);
public boolean isAdd(Element e);5. Testing
Testing validates code correctness and should also be clean.
5.1 Test‑Driven Development (TDD)
Write failing tests first, then write minimal code to pass them, and refactor.
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 Tools
IDEA plugins such as Squaretest (paid) and TestMe (free) can generate test skeletons automatically.
6. Conclusion
Writing clean code improves readability, extensibility, and overall software quality.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.