Return to site

🧩📦 DATA CLUMPS: SPOT IT, FIX IT

· code-smell,cleancode
Section image

🔸 TL;DR

▪️ Data Clumps = the same group of fields (e.g., street, city, zip, or startDate, endDate) traveling together across methods/classes.

▪️ They inflate signatures, duplicate logic, and hide domain concepts.

▪️ Fix by introducing a Value Object / Parameter Object, move behavior next to data, and let invariants live in one place.

🔸 WHAT IT LOOKS LIKE

▪️ Repeated parameter packs: createUser(name, street, city, zip, country)… everywhere.

▪️ The same trio/quartet appears in fields across multiple classes.

▪️ Copy-pasted validation/parsing for those fields in many spots.

🔸 WHY IT HURTS

▪️ Duplication: validation, formatting, and parsing repeated.

▪️ Low cohesion: related data is scattered, not encapsulated.

▪️ Fragility: adding a new field forces wide changes.

▪️ Hidden domain: meaningful concepts (e.g., Address, Money, DateRange) stay implicit.

🔸 HOW TO FIX (REFCTORINGS)

▪️ Introduce Parameter Object / Value Object: wrap the clump into a named type.

▪️ Move Behavior to the Object: put validation, formatting, comparison where the data lives.

▪️ Replace Data Clumps with Calls to the New Type across methods/fields.

▪️ Enforce Invariants inside the object (e.g., zip format, date range validity).

▪️ Prefer Immutability (e.g., records) to keep it simple and safe.

▪️ Add Factory/Builder only if construction is complex.

🔸 MINI EXAMPLE (JAVA)

// ❌ Before

void ship(String street, String city, String zip, String country) { /* ... */ }

// ✅ After

public record Address(String street, String city, String zip, String country) {

public Address {

if (zip == null || zip.isBlank()) throw new IllegalArgumentException("Zip required");

}

public String asSingleLine() { return "%s, %s %s, %s".formatted(street, zip, city, country); }

}

void ship(Address address) { /* use address.asSingleLine() */ }

🔸 PRACTICAL CHECKLIST

▪️ Scan signatures for 3–5 params that repeat across methods.

▪️ Name the concept those fields represent (Address, Money, GeoPoint, DateRange…).

▪️ Create a type, migrate callers gradually, add unit tests around the new type.

▪️ Delete duplicate logic after moving behavior in.

▪️ Lock it down: make it immutable, validate in the constructor/factory.

🔸 TAKEAWAYS

▪️ Elevate data to domain concepts—your code becomes clearer and safer.

▪️ One place for rules means fewer bugs and easier changes.

▪️ Better APIs: shorter method signatures, higher cohesion, stronger invariants.

#️⃣ s

#CleanCode #CodeSmells #Refactoring #SoftwareCraftsmanship #OOP #DDD #Java #Programming #TechLeadership #Maintainability #Readability #BestPractices 🚀

Go further with Java certification:

Java👇

Spring👇