liveBook · Manning

Shotgun surgery

As explained in Practices of the Python Pro

Shotgun surgery is a refactoring smell in which a single change requires many small modifications across a software system.

Shotgun surgery is a refactoring smell: one feature or behavior change forces many small edits across functions, methods, or modules. Like shotgun pellets, the changes are scattered rather than contained. This usually signals mixed concerns, tight coupling, or opportunities for better abstraction and encapsulation. section 7.1.1 section 10.2.2

Replacing scattered conditionals with a mapping

A long if/elif chain repeats behavior in several branches, so changing the behavior requires finding and editing multiple locations. A dictionary can map choices to outcomes instead: choices = {'A': 'apples', 'B': 'bats'}; print(f'{choice} is for {choices[choice]}'). Adding a choice then becomes a focused data change rather than another conditional branch. section 7.1.2

Reduce shotgun surgery by making changes easier to localize:

  • Separate concerns so persistence, business logic, and user interaction have clearer homes. section 7.1.1
  • Use decomposition, encapsulation, and abstraction to reduce resistance to change. section 7.1.2
  • When edits jump between modules, investigate tight coupling and move behavior to a better-suited class or module. section 10.2.2

How Practices of the Python Pro covers it

How deep it goes
Explains the smell, its coupling-related causes, and refactoring directions, but stops short of a complete refactoring workflow.
Examples
Uses Bark architecture, nested conditionals, dictionary mappings, database modules, command classes, and menu options.
What you can do after
Diagnose scattered changes and refactor behavior toward focused modules, mappings, encapsulation, and looser coupling.
How it connects
Connects shotgun surgery with extensibility, flexibility, tight coupling, loose coupling, decomposition, encapsulation, abstraction, and separation of concerns.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.