Return to site

🧹🚩 REMOVE FLAG ARGUMENT REFACTORING (MAKE YOUR METHODS SAY WHAT THEY DO)

· cleancode,craftsmanship,programmmer,techlead

🔸 ✅ TL;DR

Flag arguments (boolean/enum/string) make methods do multiple jobs. Split them into explicit methods (or objects) so the code tells the truth: premium vs regular is visible, testable, and easier for tooling to analyze.

Section image

🔸 THE PROBLEM: “FLAG ARGUMENTS” HIDE INTENT 🤯

A flag argument is when a method changes behavior based on a parameter like:

▪️ boolean isPremium ✅

▪️ String mode = "PREMIUM" 😬

▪️ enum Tier { PREMIUM, REGULAR } ✅ (better than String, still a flag)

It works, but it forces readers (and tools) to mentally simulate branches: “What happens when it’s premium… and when it’s not?” 🧠💥

🔸 BEFORE: ONE METHOD, MULTIPLE PERSONALITIES 🎭

public Invoice total(User user, boolean premium) {

if (premium) {

return premiumTotal(user); // special rules 💎

}

return regularTotal(user); // standard rules 🧾

}

Or worse with Strings 😅:

public Invoice total(User user, String mode) {

if ("PREMIUM".equals(mode)) { ... }

else { ... }

}

🔸 AFTER: SPLIT INTO EXPLICIT METHODS (OR OBJECTS) ✅

public Invoice totalPremium(User user) {

return premiumTotal(user);

}

public Invoice totalRegular(User user) {

return regularTotal(user);

}

Even better if you want a single entry point:

public Invoice total(User user, Tier tier) {

return switch (tier) {

case PREMIUM -〉> totalPremium(user);

case REGULAR -〉 totalRegular(user);

};

}

➡️ The key: the premium vs regular logic becomes named, not hidden behind a flag.

🔸 WHY IT’S WORTH IT (HUMANS + TOOLS) 🤝🛠️

▪️ Clearer intent: totalPremium() reads like a sentence.

▪️ Fewer “what does true mean?” moments: total(user, true) is ambiguous.

▪️ Better code analysis: premium logic and regular logic become separate “units” → tools can reason about them more precisely (complexity, coverage, duplication, hotspots).

▪️ Easier to test: one behavior per method → smaller, focused tests.

▪️ Safer evolution: adding “VIP” later is cleaner than expanding a growing if/else tree.

🔸 WHEN FLAGS ARE A SMELL 🚨

▪️ If the method name doesn’t explain the argument (doStuff(user, true) 🤡)

▪️ If the method has multiple branches + different rules

▪️ If reviewers keep asking “what does this mode do?”

🧠 TAKEAWAYS

▪️ Prefer explicit method names over true/false behaviors.

▪️ If you must keep a single entry point, delegate to named methods.

▪️ Your future self (and your static analysis tools) will thank you. 😄

#Refactoring #CleanCode #SoftwareDesign #Java #CodeQuality #Testing #SOLID #Maintainability #DeveloperTools #StaticAnalysis

Go further with Java certification:

Java👇

Spring👇

SpringBook👇