Fundamentals 18 min read

Clean Code Principles: Naming, Classes, Functions, and Testing Practices

This article explains why clean code is essential for productivity and project health, covering naming conventions, class design, SOLID principles, function design, parameter handling, testing strategies like TDD and the FIRST principles, and tools such as SonarLint to maintain code quality.

Top Architect
Top Architect
Top Architect
Clean Code Principles: Naming, Classes, Functions, and Testing Practices

1. Why Keep Code Clean?

Unclean code accumulates over time, reducing productivity, causing bugs, crashes, overtime, higher hiring costs, and even risking company failure.

Hard to extend, may introduce new bugs.

System crashes.

Increased overtime.

Higher staffing costs.

Potential company collapse.

1.1 Start Clean

Write clean code from the beginning; if dirty code appears, refactor immediately. Never postpone cleanup.

later equal never

2. Naming

Good names improve readability, reduce understanding cost, and lower overtime.

2.1 Bad Naming Examples

public interface Animal {
    void abc();
}

The method abc() gives no clue about its purpose.

2.2 Good Naming Examples

public interface Animal {
    void cry();
}

Now the purpose is obvious.

2.3 Inconsistent Naming

public interface StudentRepository extends JpaRepository
{
    Student findOneById(@Param("id") String id);
    List
queryAllStudent();
}

public interface StudentRepository extends JpaRepository
{
    Student findOneById(@Param("id") String id);
    List
findAll();
}

Standardize method names for consistency.

2.4 Redundant Naming

// Get a single object
getXxx();
// Get multiple objects
listXxxx();

Avoid unnecessary words in identifiers.

3. Classes

Clean classes should follow single responsibility, open‑closed principle, and high cohesion.

3.1 Single Responsibility

Each class should have one reason to change; large classes usually violate this.

public abstract class Sql {
    // operate SQL
    public abstract void insert();
    // count SQL operations
    public abstract void countInsert();
}

public abstract class CountSql {
    public abstract void countInsert();
}

Separate responsibilities into different classes.

3.2 Open‑Closed Principle

Modules should be closed for modification but open for extension.

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 */ }
}

Adding new behavior (e.g., delete) only requires a new subclass.

3.3 Cohesion

High cohesion means a class’s methods share related data; low cohesion suggests the class should be split.

4. Functions

Clean functions should do one thing, have expressive names, simple parameters, and clear return values.

4.1 Do One Thing

Break long methods into small, focused steps.

public class PicService {
    public String upload() {
        // validate image (80 lines)
        // compress image (50 lines)
        // return status (5 lines)
        return "0";
    }
}

public String upload() {
    check();
    compress();
    return "0";
}

4.2 Function Naming

Names should describe intent; avoid ambiguous names like addCharacter without indicating position.

public String appendCharacter(String origin, char ch);
public String insertCharacter(String origin, char ch, int position);

4.3 Parameters

Prefer few parameters; encapsulate related data into objects.

public List
findStudent(int age, String name, String country, int gender);
public List
findStudent(Student student);

4.4 Return Values

Separate commands from queries; use exceptions instead of error codes.

public void addElement(Element e);
public boolean isAdd(Element e);

public void sendShutDown() {
    try {
        tryToShutDown();
    } catch (DeviceShutDownError e) {
        logger.log(e);
    }
}

private void tryToShutDown() throws DeviceShutDownError { /* ... */ }

5. Testing

Testing validates code correctness; test code should also be clean.

5.1 TDD

Write failing tests first, then implement just enough code to pass.

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

IDE plugins such as Squaretest (paid) and TestMe (free) can generate unit tests.

6. Code Quality Tools

SonarLint helps detect duplicated code, potential NPEs, and suggests using modern APIs like LocalDate instead of Date .

7. Conclusion

Writing clean code improves readability, extensibility, development efficiency, reduces overtime, and raises the developer’s skill level. Every developer should read "Clean Code" and practice these principles from the start rather than relying on later refactoring.

testingsoftware designrefactoringclean codenaming-conventions
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.