Backend Development 4 min read

Avoiding Low Cohesion Bugs by Centralizing Repayment Logic in Java

The article explains how adding a new reducePrincipal field to the RepayPlan class caused existing interfaces to miscalculate remaining principal, and demonstrates fixing the low‑cohesion bug by centralizing the updated calculation in a RepaymentCalculator utility so future changes occur in one place.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Avoiding Low Cohesion Bugs by Centralizing Repayment Logic in Java

In a recent code change a colleague introduced a new field reducePrincipal to the RepayPlan class, but several existing interfaces still calculated the remaining principal without considering this field, leading to a bug.

Original RepayPlan class:

public class RepayPlan {
    private long principal;          // 本金
    private long interest;           // 利息
    private long fee;                // 费用
    private long totalAmt;           // 总金额
    private long repaidPrincipal;   // 已还本金
    private long repaidInterest;    // 已还利息
    private long repaidFee;          // 已还费用
    private long totalRepaidAmt;     // 总的已还金额
    // getters and setters omitted for brevity
}

After adding reducePrincipal :

public class RepayPlan {
    // ... previous fields ...
    private long reducePrincipal;   // 减免本金 (new field)
}

Three interfaces originally computed remaining principal as:

public long calculateRemainingPrincipal(RepayPlan plan) {
    return plan.getPrincipal() - plan.getRepaidPrincipal();
}

and similarly for simulation and query methods.

The required logic changed to:

remainingPrincipal = principal - repaidPrincipal - reducePrincipal

To avoid duplicated changes, a utility class RepaymentCalculator is introduced to centralize the calculation:

public class RepaymentCalculator {
    // Calculate remaining principal
    public static long calculateRemainingPrincipal(RepayPlan plan) {
        return plan.getPrincipal() - plan.getRepaidPrincipal() - plan.getReducePrincipal();
    }
}

All three interfaces now delegate to this single method, ensuring future changes are made in one place.

backendJavacode refactoringdesign patternlow cohesion
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

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.