Video in progress
What is the difference between the "shotgun surgery" and "divergent change" code smells, and which principle do they violate?
Shotgun surgery means one change requires editing many classes (the logic is scattered). Divergent change means one class changes for many different reasons. Both are two sides of broken cohesion and the Single Responsibility principle.
📖 Answer
They are mirror images of each other.
A shotgun surgery example: to add a new currency (KZT) you have to edit PriceFormatter, ExchangeService, InvoicePdf, ReportExporter, the CurrencyDto for the frontend and the CHECK constraint in SQL. If you forget one, the bug appears on prod only in a report. It's a sign that the "knowledge about currency" is scattered over many places. The fix is to gather it in one place: the Currency enum or value object knows its own format, precision and symbol.
A divergent change example: the OrderService class gets edited when the price formula changes, when the delivery rule changes and when the SMS text changes. Three teams, three reasons, one file: merge conflicts and changes that break each other. The fix is to split the class by reasons for change: PricingPolicy, DeliveryPolicy, OrderNotifier.
How to find them: git history shows it very well.
# which files change the most (candidates for divergent change)
git log --since=6.months --name-only --pretty=format: | sort | uniq -c | sort -rn | head
# which files always change together (a sign of shotgun surgery)
git log --since=6.months --name-only --pretty=format:'---'
By analyzing the output of the second command you can count the pairs of files that show up together in one commit (tools like CodeScene call this "change coupling"). Files that always change together but live in different packages are knowledge that should be merged.
Sign up to mark studied questions and save your progress.