Video in progress
How do you identify and refactor the god class and feature envy code smells?
A god class is a huge class that knows and does too much. Feature envy is a method that works more with another class's data than with its own class. The first is fixed by splitting the class, the second by moving the method to the owner of the data.
📖 Answer
A feature envy example:
class InvoicePrinter {
String line(OrderItem item) {
BigDecimal price = item.getUnitPrice()
.multiply(BigDecimal.valueOf(item.getQuantity()))
.subtract(item.getDiscount());
return item.getName() + ": " + price;
}
}
The method reaches into four fields of OrderItem and uses nothing from its own class. We move the calculation to its owner:
// inside OrderItem
BigDecimal lineTotal() {
return unitPrice.multiply(BigDecimal.valueOf(quantity)).subtract(discount);
}
Now lineTotal() can be reused elsewhere, and InvoicePrinter only formats.
Signs of a god class:
- 1500+ lines, 30+ methods, 15+ fields;
- a name like
OrderManager,MainService,CommonUtils; - methods work with different groups of fields, with no overlap between the groups;
- nearly every PR in every sprint changes it.
The order of splitting (the safe way):
- Tests first: characterization tests for at least the main flows.
- Map which methods use which fields; the ones used together are candidates for one class.
- Move them in small steps with the IDE's "Extract Class" / "Move Method" refactorings, running tests after every step.
- The old class can stay for a while as a facade, and then the callers are moved to the new classes.
Static analysis (cognitive complexity in Sonar, class size) helps find candidates, but make the decision with domain knowledge.
Sign up to mark studied questions and save your progress.