Clean Code Principles and Practical Java Refactoring Guidelines

This article presents a comprehensive guide to improving Java code quality by emphasizing simplicity, leveraging language features, consolidating similar logic, and structuring APIs to clearly distinguish required and optional parameters, illustrated with side‑by‑side bad and good implementations and practical recommendations.

High Availability Architecture
High Availability Architecture
High Availability Architecture
Clean Code Principles and Practical Java Refactoring Guidelines

The article explores how to write clean, maintainable Java code by applying the "大道至简" (simplicity) principle, using language features wisely, keeping code tidy, and preserving a clear business‑process framework.

2.1 Simplicity – A comparison of a convoluted processor lookup with a concise hash‑map access demonstrates that unnecessary loops and string parsing obscure intent. The "bad" implementation iterates over the entire map and splits keys, while the "good" version builds the key directly and retrieves the processor in one call.

//key = sNo_dNo_bType
private Map<String, Processor> processorMap = new HashMap<>();
//糟糕实现
private Processor getProcessor(DataDto dataDto) {
    for (Map.Entry<String, Processor> entry : processorMap.entrySet()){
        if (entry.getKey().contains(dataDto.getSellerNo())){
            String[] keyArr = entry.getKey().split("_");
            if (keyArr[1].contains(dataDto.getDeptNo()) && keyArr[2].equals(dataDto.getBizType())) {
                return entry.getValue();
            }
        }
    }
    return null;
}
//优秀实现
private Processor getProcessor(DataDto dataDto) {
    String key = dataDto.getSNo() + "_" + dataDto.getDNo() + "_" + dataDto.getBType();
    return processorMap.get(key);
}

The analysis notes that the concise version is easier to understand and less error‑prone.

2.2 Leveraging Language Features – Using Optional and stream APIs reduces boilerplate. For null‑checking and trimming strings, the traditional if (msg != null) guard is replaced by a one‑liner.

public String trim(String message) {
    if (message != null) {
        return message.trim();
    }
    return message;
}
public String trim(String message) {
    return Optional.ofNullable(message).orElse("").trim();
}

Similarly, grouping a list of names by prefix is simplified with Collectors.groupingBy:

Map<String, List<String>> map = new HashMap<>();
for (String name : nameList) {
    String[] split = name.split("-");
    List<String> names = map.get(split[0]);
    if (null == names) {
        names = new ArrayList<>();
    }
    names.add(name);
    map.put(split[0], names);
}
Map<String, List<String>> nameMap = nameList.stream()
    .collect(Collectors.groupingBy(o -> o.split("-")[0]));

2.3 Reasonable Use of Language Features – Constructors that enforce required fields prevent incomplete objects. The "bad" approach creates a bean and sets fields individually, risking missing mandatory data. The "good" approach provides a constructor with required arguments.

//普通实现
Personnel personnel = new Personnel();
personnel.setName("张三");
personnel.setIdNumber("123123123123123123");
//优秀实现
public class Personnel {
    private String name;
    private String idNumber;
    // ... other fields ...
    public Personnel(String name, String idNumber) {
        this.name = name;
        this.idNumber = idNumber;
    }
}
Personnel personnel = new Personnel("张三","123123123123123123");

Response handling follows the same pattern: a utility builder class returns immutable response objects instead of mutating a shared instance.

//普通实现
Response response = new Response();
if (failure) {
    response.getCode(300);
    response.setMessage("失败");
} else {
    response.getCode(200);
    response.setMessage("成功");
}
//优秀实现
public final class WebResponseBuild {
    private WebResponseBuild() { throw new IllegalStateException("Utility class"); }
    public static <T> WebResponse<T> success(String requestNo) {
        return new WebResponse<>(requestNo, DEFAULT_SUCCESS.getCode(), DEFAULT_SUCCESS.getMessage(), null);
    }
    public static <T> WebResponse<T> error(String requestNo, StatusCode messageCode) {
        return new WebResponse<>(requestNo, messageCode.getCode(), messageCode.getMessage(), null);
    }
}
return WebResponseBuild.success("123213");

2.4 Keep Code Tidy – The article advises limiting class size (< 1000 lines) and method size (< 100 lines) to maintain single responsibility and improve readability.

2.5 Preserve Clear Business Flow – Core business orchestration should remain in a thin layer, while validation, transformation, and auxiliary logic are extracted into dedicated helpers or services.

2.6 Prohibited Practices – Avoid massive classes, large method blocks, and designs that modify input objects to return results, as they increase coupling and hinder maintainability.

The concluding remarks reiterate that adhering to these principles yields code that is easy to read, test, and evolve, echoing the "大道至简" philosophy.

References include "Writing High‑Quality Code: 151 Recommendations for Java" and "Design Patterns in Plain Language", as well as tools like SonarLint for continuous quality enforcement.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaRefactoringclean code
High Availability Architecture
Written by

High Availability Architecture

Official account for High Availability Architecture.

0 followers
Reader feedback

How this landed with the community

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.