Scrivio Interview library
ConceptIntermediate7 min read · updated 12 November 2026

Explain the code smells feature envy, shotgun surgery and divergent change, with examples from a Spring codebase and the refactorings that address each.

Feature envy is a method that works mostly on another object's data, such as OrderService computing an order's total from its lines; we move the method onto Order. Shotgun surgery is when one small change, like adding a field, forces edits in a DTO, mapper, entity, validator and several services; we consolidate the logic and cut duplicate models. Divergent change is one class that changes for many unrelated reasons; we split it by responsibility. All three often grow from anemic domain models and package-by-layer structures, and version control history shows where they are.

Why this question is asked

These three smells explain why many Spring codebases feel slow to change even when every class looks tidy on its own. They are not about a single ugly method; they are about where logic lives and how changes ripple through the code. Interviewers ask about them to see whether we can connect everyday pain, such as 'every ticket touches nine files', to a design cause and a concrete refactoring. In this answer, we will recap what a smell is, look at each of the three with a Spring example and its fix, see the common root they share, and finish with how to find them using git history.

1A Quick Recap of Code Smells

A code smell is a surface sign that the design underneath may be making change harder than it should be. It is not a bug and it does not break the build. The three smells in this question are all about the relationship between data and the behaviour that uses it.

There is a helpful way to remember the last two. Shotgun surgery is one change that hits many classes. Divergent change is one class that is hit by many changes. They are mirror images of each other, and both mean our boundaries do not match the way the business actually changes.

Three smells at a glance
SmellSymptomTypical refactoring
Feature envya method uses another object's getters more than its own fieldsMove Method onto the data's owner
Shotgun surgeryone change edits many classes in many placesMove Method/Field, merge duplicate models
Divergent changeone class edited for many unrelated reasonsExtract Class by responsibility

2Feature Envy: OrderService Doing Order's Job

A method has feature envy when it is more interested in another class's data than in its own. The classic Spring example is a service that reaches into an entity through getters to calculate something about it.

Java
@Service
class OrderService {
BigDecimal total(Order order) {
BigDecimal sum = BigDecimal.ZERO;
for (OrderLine line : order.getLines()) {
sum = sum.add(line.getUnitPrice().multiply(BigDecimal.valueOf(line.getQuantity())));
}
if (order.getCoupon() != null) sum = sum.subtract(order.getCoupon().getAmount());
return sum.max(BigDecimal.ZERO);
}
}

Notice that the method never uses anything from OrderService itself; it only calls getters on Order, OrderLine and Coupon. The data and the rule live in different places, so every other class that needs a total either calls this service or, worse, writes its own version. The refactoring is Move Method: put the logic where the data lives.

3Moving the Behaviour to the Data

After the move, Order answers the question about itself, and each line knows its own subtotal.

Java
@Entity
class Order {
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL) private List<OrderLine> lines = new ArrayList<>();
@Embedded private Coupon coupon;
BigDecimal total() {
BigDecimal sum = lines.stream().map(OrderLine::subtotal).reduce(BigDecimal.ZERO, BigDecimal::add);
return coupon == null ? sum : sum.subtract(coupon.amount()).max(BigDecimal.ZERO);
}
}
order.total(); // 42.50, the same everywhere it is asked

The rule now exists once, it can be unit tested without Spring, and the getters that existed only to feed the service can often disappear. The service is left with what services are for: coordinating a use case, such as loading the order, calling order.total() and charging the payment.

4Shotgun Surgery: One Field, Nine Edits

Shotgun surgery is when a single, small change scatters edits across the codebase. Suppose the business asks us to store a customer's loyalty tier. In a typical layered Spring service, we add the field to CustomerEntity, CustomerDto, CreateCustomerRequest and CustomerResponse; update CustomerMapper in both directions; add a rule to CustomerValidator; and adjust the discount logic, which is duplicated in PricingService, CheckoutService and InvoiceService. That is nine files for one idea, and forgetting any one of them produces a quiet bug, for example an invoice that ignores the tier.

The fix is to bring together what changes together. We move the duplicated discount rule into one place, often onto a domain object such as Customer.discountRate(). We question each extra model: if CustomerDto and CustomerResponse are identical, one can go. Where we do need separate models, for example to keep the API contract stable, we generate the boring mapping with a tool such as MapStruct, so adding a field does not mean editing hand-written mapping code. The goal is that a new field touches the places that genuinely have to know about it, and nowhere else.

5Divergent Change: The Class Everyone Edits

Divergent change is the mirror image: one class keeps changing, for unrelated reasons. An OrderService of 2,000 lines might change when the pricing team changes discounts, when marketing changes confirmation emails, when finance changes tax rules, and when the warehouse changes allocation. Four teams editing one file means merge conflicts, tests that break for unrelated reasons and reviews that need four kinds of expertise.

The refactoring is Extract Class along the lines of those reasons: OrderPricing, OrderNotifications, TaxCalculator and StockAllocation, with OrderService reduced to coordinating them, or removed entirely. This is the single responsibility principle in practical form: a class should have one reason to change, meaning one group of people whose requests change it.

6The Common Root: Anemic Models and Package-by-Layer

These smells usually share a cause. An anemic domain model is one where entities are just fields with getters and setters, and all behaviour lives in services. That design invites feature envy by definition, because services must reach into entities to do anything. It invites shotgun surgery because the same rule gets written in several services, and divergent change because a few big services collect every rule.

Package-by-layer makes it worse. When the code is organised into controller, service, repository and dto packages, everything about customers is spread across four folders, and nothing stops a pricing rule from appearing in three services. Package-by-feature, with packages such as order, pricing and customer that each hold their own controller, service, entities and repository, keeps related code together and lets us make most classes package-private, so other features cannot reach in.

7Finding the Smells in Version Control History

We do not have to guess where these smells are. Git already records which files change, how often, and which change together. Two quick commands give a useful first picture.

YAML
# Files changed most often in the last six months (divergent change candidates)
git log --since="6 months ago" --name-only --pretty=format: -- src/main | sort | uniq -c | sort -rn | head
# 87 src/main/java/com/shop/order/OrderService.java
# 41 src/main/java/com/shop/customer/CustomerMapper.java
# How many files each commit touched (shotgun surgery candidates)
git log --since="6 months ago" --pretty=format:%h --shortstat | grep "files changed" | sort -rn | head

A file that changes far more often than its neighbours is a divergent change candidate. Groups of files that keep appearing in the same commits, which tools such as code-maat or CodeScene measure as change coupling, point to shotgun surgery. Combining change frequency with file size or complexity gives a short list of hotspots where refactoring pays back fastest.

8Follow-up questions

Is a rich domain model always better than putting logic in services?

Not always. Logic that is about one object's own data, such as an order's total or whether it can be cancelled, belongs on that object. Logic that coordinates several aggregates, calls external systems or manages transactions belongs in a service. The smell is not 'services have logic'; it is a service that only manipulates another object's fields.

How do you refactor a 2,000-line divergent class without breaking it?

Gradually and behind tests. We add characterisation tests around the public methods, extract one responsibility at a time into a new class that the old one delegates to, and keep each step in its own small commit. Callers can move to the new classes over time, and the old class shrinks until it can be removed.

Can removing DTOs to fix shotgun surgery cause other problems?

Yes. Exposing JPA entities directly in the API ties our public contract to the database schema and can leak lazy-loading problems into JSON serialisation. The aim is to remove models that add nothing, not all boundaries. Keep a separate API model where the contract must stay stable, and generate its mapping.

9Conclusion

In this answer, we looked at three smells about where logic lives. Feature envy is a method that uses another object's data more than its own, fixed by moving it onto that object. Shotgun surgery is one change that hits many classes, fixed by consolidating duplicated logic and removing models that add nothing. Divergent change is one class that changes for many reasons, fixed by extracting classes by responsibility. Anemic models and package-by-layer structures are a common root, and git history shows where the hotspots are.

What to say in the interviewAbout 90 seconds aloud

Open with

Feature envy is when a method is more interested in another class's data than its own. A typical Spring example is OrderService.total(order), which loops over order.getLines() and the coupon and never uses anything from the service.

Then, if they want more

I would move that method onto Order, so the rule exists once and can be unit tested without Spring. Shotgun surgery is when one small change forces edits in many places. Adding a loyalty tier might touch the entity, three DTOs, the mapper, the validator and discount logic duplicated in three services.

The fix is to bring together what changes together: put the discount rule in one place, drop identical models, and generate the mapping we do need with something like MapStruct. Divergent change is the mirror image: one class, like a 2,000-line OrderService, that changes for pricing, emails, tax and allocation.

I would extract classes along those reasons so each has one reason to change. All three usually come from an anemic domain model, where entities are just getters and setters and services do everything, and from package-by-layer structure, which scatters a feature across folders. Moving to richer entities and package-by-feature helps.

To find them I use git history: files that change much more often than others are divergent change candidates, and files that keep changing in the same commits point to shotgun surgery.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain the code smells feature envy, shotgun surgery and divergent change, with...": https://scrivio-interview-library.netlify.app/java/clean-code/b578a38aa3/