Fundamentals 12 min read

Principles of Clean Code: Theory and Practical Comparisons in Java

This article presents a theoretical framework for clean code, compares poor and excellent Java implementations across several scenarios, and offers practical recommendations to simplify code, leverage language features, and maintain clear business logic, emphasizing the core philosophy of "the greatest simplicity".

JD Tech
JD Tech
JD Tech
Principles of Clean Code: Theory and Practical Comparisons in Java

Introduction: The article aims to provide a theoretical mindset for code cleanliness, encouraging readers to flexibly apply technical methods under this guidance.

Practice Comparison: Demonstrates how a poorly implemented processor lookup using unnecessary loops can be replaced by a concise map lookup, highlighting the importance of understanding hash structures.

// Poor implementation
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;
}

// Excellent implementation
private Processor getProcessor(DataDto dataDto) {
    String key = dataDto.getSNo() + "_" + dataDto.getDNo() + "_" + dataDto.getBType();
    return processorMap.get(key);
}

2.1 "大道至简": Emphasizes that a principle should be expressible in one or two sentences; the same applies to using programming languages as communication tools.

2.2 "站在巨人的肩膀上": Shows how modern JDK features (Optional, StringUtils) and stream APIs replace verbose null‑checking and manual grouping logic.

// Poor null‑check
public String trim(String message) {
    if (message != null) {
        return message.trim();
    }
    return message;
}
// Excellent using Optional
public String trim(String message) {
    return Optional.ofNullable(message).orElse("").trim();
}

// Grouping list with streams
Map<String, List<String>> nameMap = nameList.stream()
    .collect(Collectors.groupingBy(o -> o.split("-")[0]));

2.3 "合理使用语言特性": Demonstrates constructor overloading and builder patterns to enforce required fields, reducing errors from missing mandatory data.

public class Personnel {
    private String name;
    private String idNumber;
    // ... other fields
    public Personnel(String name, String idNumber) {
        this.name = name;
        this.idNumber = idNumber;
    }
}

2.4 "保持代码卷面整洁": Shows how to filter collections using streams instead of manual iteration and removal.

private List<BatchAttr> getProductionDateAttr(PoBatchRel batchRel) {
    return Optional.ofNullable(batchRel)
        .map(PoBatchRel::getBatchAttrList)
        .orElseGet(ArrayList::new)
        .stream()
        .filter(attr -> Objects.equals(BatAttrMapping.PD.getKeyOmc(), attr.getBatchKey()))
        .collect(Collectors.toList());
}

2.5 "保持业务流程主体框架明了": Advises keeping the main business flow concise, extracting validation, conversion, and auxiliary logic into separate classes or methods.

2.6 "禁止项": Lists prohibitions such as classes exceeding 1,000 lines, methods exceeding 100 lines, and mutating input objects across class boundaries, emphasizing single‑responsibility and low coupling.

Recommendation: Use proven tools (e.g., SonarLint) and libraries to reduce repetitive code, improve safety, and focus development effort on core business logic.

Conclusion: By adhering to the "greatest simplicity" philosophy, developers can keep primary business logic clear, encapsulate details, and leverage language features and existing utilities to avoid low‑level errors and redundant implementations.

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.

JavaCode Refactoringbest practicesclean code
JD Tech
Written by

JD Tech

Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.

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.