Start free trial
Trending New Genres Authors
EnglishEnglish
EspañolSpanish
简体中文Chinese
繁體中文Chinese (Traditional)
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Searching...
SoBrief
Refactoring

Refactoring

Improving the Design of Existing Code
Make the next feature cheaper to build by changing the code without changing what it does.
by Martin Fowler 1999 431 pages
4.24
8k+ ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

Key Takeaways

Refactor before adding features when the current design makes change expensive

Change exposes design. Fowler opens with a video-store program that calculates rental charges and loyalty points inside one long customer method. It works, but a request for an HTML statement would encourage copying the method. Later changes to movie pricing could then require fixing both copies, with the risk of inconsistent rules. The better sequence is to improve the structure that blocks the requested change, then add the feature.

Structure is a practical asset. Refactoring means altering a program's internal organization without changing what users observe. In the example, calculations are separated from formatting, so both plain-text and HTML statements can reuse them. The benefit is not code beauty for its own sake. It is fewer places to search, understand, and update when requirements shift.

Analysis

This is a useful inversion of the familiar pressure to start coding the requested feature immediately. The proposed design work is justified by a concrete obstacle, not by an abstract pursuit of elegance. In economic terms, refactoring is an investment whose return depends on how often the affected code changes. The argument is strongest in long-lived systems with evolving rules. For a throwaway script, the future maintenance cost may never arrive, so the same investment could be wasteful.

Build fast, self-checking tests, then change one small thing at a time

Tests make change visible. Before altering the video-store program, Fowler creates tests that compare generated statements with checked examples. A self-checking test reports whether the result matches, rather than asking someone to inspect output by hand. Tests run after each small transformation, narrowing the search for mistakes. During an extraction, a return type was accidentally changed from a decimal to an integer. The tests quickly exposed the lost fractional charges.

Small steps limit damage. The working rhythm is test, change, test. Tests should focus on risky behavior, especially boundaries and error cases, rather than mechanically covering every simple accessor. A reported bug should first become a failing test, which both clarifies the defect and guards against its return. This safety net is essential even when automated refactoring tools are available.

Analysis

The tests function as a feedback-control system: make a change, observe the result, and correct course before uncertainty accumulates. That is also a cognitive advantage. When a failure follows one small edit, the relevant code is still fresh in the programmer's mind. The method does not make a program proven correct, and a test suite can miss unanticipated cases. Its more modest promise is powerful: it makes ordinary mistakes cheaper to detect and discourages risky, invisible leaps.

Move each responsibility toward the data and changes it serves

Put behavior near its knowledge. In the rental example, the customer initially calculates each charge by inspecting rental and movie information. Moving the charge calculation to the rental, and then locating pricing differences with movie type, reduces how much the customer must know. The statement method can focus on assembling a statement instead of also owning pricing rules and reward calculations.

Separate reasons to change. A class is hard to maintain when unrelated changes repeatedly land in it, or when one change forces edits across many classes. Fowler calls these patterns divergent change and shotgun surgery. Moving fields and methods, or extracting a class, can bring together the code that changes for the same reason. This is a heuristic, not a mechanical law: behavior that uses several objects may have more than one plausible home.

Analysis

The principle resembles information hiding: a component should contain decisions that its clients do not need to understand. It also offers a practical way to assess class boundaries: ask which facts a method repeatedly requests, and which changes tend to arrive together. Yet putting behavior beside data is not always optimal. Shared policies, security boundaries, and dependencies between services can outweigh proximity. The useful question is not simply, "Which object owns this data?" but, "Which placement makes likely changes local without creating a worse dependency?"

Use code smells to find likely trouble, not to enforce aesthetic rules

Smells are invitations to investigate. Fowler and Kent Beck name recurring warning signs, including duplicated code, long methods, oversized classes, feature envy, and repeated conditional logic. A long method may hide several distinct tasks; repeated code may mean a rule is maintained in multiple places. The smell suggests where to look, while a fitting refactoring provides a possible remedy.

Context decides the cure. Similar code in sibling classes may be combined in a superclass, while a method that mostly uses another object's data may belong elsewhere. Comments can reveal code that needs a clearer method name, but comments themselves are not condemned. Nor does every subclass need to be eliminated. The authors explicitly treat smells as clues that require judgment, not measurements that determine a design automatically.

Analysis

This diagnostic vocabulary is valuable because teams can discuss observable structures rather than arguing over whether code feels ugly. It makes design review more concrete: point to duplicated rules, then ask whether they change together. The danger is turning a smell list into a compliance checklist. A small amount of duplication can be clearer than an elaborate abstraction, and a long method can be straightforward if its steps form one coherent operation. The right test is whether the structure makes a real change harder or riskier.

Replace repeated type decisions with polymorphism when variation keeps spreading

Keep changing rules contained. The video-store program uses a switch on movie price category to calculate charges. When pricing and reward rules vary by category, similar conditionals can spread through the system. Fowler first locates the category-dependent behavior with the movie, then replaces the branching logic with separate price objects that provide the appropriate behavior. The rest of the program asks for a charge without knowing which pricing case applies.

Choose the right variation mechanism. Subclasses can represent fixed types, but they cannot change an object's class during its lifetime. When a movie's category can change, a separate state or strategy object can be replaced instead. This approach is worth its added structure when new types or rules are likely. For a few stable cases in one method, polymorphism may be more machinery than the problem needs.

Analysis

Polymorphism turns a growing list of decisions into a stable request with interchangeable implementations. That can localize change and reduce the chance that one conditional is updated while another is forgotten. The crucial phrase is "when variation keeps spreading." Abstraction has a carrying cost: extra classes, indirection, and concepts a maintainer must learn. A good design does not eliminate every conditional. It prevents volatile decisions from being duplicated across places that must remain synchronized.

Choose a simple design when future flexibility is only a guess

Design for what is known. Refactoring changes the role of upfront design. A team still needs a plausible plan, but it need not build every imagined extension into the first version. If future requirements arrive, the structure can be reshaped before the new feature is added. Fowler's Rule of Three captures one practical trigger: tolerate the first instance, notice the second repetition, and consider refactoring when the pattern appears a third time.

Separate the two kinds of work. The book describes switching between adding functionality and refactoring. While adding a feature, behavior changes. While refactoring, behavior should stay the same. Keeping these intentions distinct helps tests reveal whether a structural edit accidentally altered results. The approach favors gradual design improvement over either perfect prediction or uncontrolled cleanup.

Analysis

This is a form of option management: avoid paying today for flexibility whose value is uncertain, while keeping the code easy enough to reshape if that value becomes clear. It counters overengineering without endorsing carelessness. The Rule of Three is a useful prompt, not a universal threshold; a risky duplication in a critical calculation may deserve attention immediately, while three trivial repetitions may be harmless. The deeper discipline is to distinguish evidence about present change from speculation about every possible future.

Profile first, then optimize the small hot spots that matter

Measure before guessing. During work on the Chrysler Comprehensive Compensation system, developers suspected several causes of slow performance. Profiling instead showed that the program spent much of its time creating date-range objects, many of them empty. Reusing a single empty range doubled the system's speed. In another account, payroll processing was initially estimated to take more than 1,000 hours; successive measured improvements reduced the runtime to 40 hours, then 12, and eventually a couple of hours after parallel execution.

Make code tunable first. Fowler argues for clear, well-factored code followed by profiling and focused optimization. A profiler identifies where time and memory are actually spent. Small changes can then be tested and measured, and ineffective optimizations discarded. The short-term cost of extra method calls or repeated calculations does not, by itself, establish a meaningful performance problem.

Analysis

Profiling is a form of disciplined uncertainty reduction. A programmer's mental model of a running system is often incomplete, especially when costs emerge from frameworks, storage, or object allocation. Clear structure makes a bottleneck easier to isolate, while measurement protects teams from optimizing code that users barely exercise. There are limits: hard real-time systems may require budgets from the outset, and the book's examples concern measured performance in particular systems. The general lesson is not to postpone every performance concern, but to match the method to the cost of being slow.

Refactor legacy systems in small slices, and stop when confidence runs out

Large repairs need a direction. Some problems require broad changes, such as separating user-interface code from business rules or splitting an inheritance hierarchy that mixes two kinds of variation. These efforts may take months, so the book recommends advancing through small changes while doing necessary feature work, rather than halting a project for a wholesale cleanup. Team agreement matters when many components and developers are affected.

Know the limits of safety. Tests, compilers, and refactoring tools reduce risk but cannot guarantee that every behavior is preserved. Published interfaces may have callers outside the team, database changes may require difficult data migration, and reflection can hide references from ordinary code searches. If a change becomes hard to verify, stop or revert to the last known working version. Refactoring should serve delivery, not become an endless project of its own.

Analysis

The stopping rule is an important complement to the book's confidence in incremental change. A refactoring process depends on trustworthy feedback, and confidence should fall when tests are weak, interfaces are external, or the architecture crosses hard operational boundaries. This also makes refactoring a team practice, not only an individual coding skill: shared ownership, review, and compatible deployment affect whether a local improvement is safe. Incrementalism lowers risk, but it cannot erase organizational constraints or make every legacy system economical to reshape.

Analysis

Refactoring is both a technical method and a theory of how software design should evolve. Its central wager is that design is not a one-time blueprint. Developers learn what a system needs while building and changing it, so the internal structure must remain revisable. Small behavior-preserving transformations make that revision less hazardous and let implementation knowledge accumulate in the code itself.

The book's strongest narrative choice is the video-store example. A working but tangled statement routine is not presented as a moral failure. It becomes a liability when new output formats and changing pricing rules arrive. That distinction grounds refactoring in the economics of change: improve a structure when a concrete task exposes its cost. The example also demonstrates that architecture is not merely a diagram. It is the location of decisions, and therefore the number of places a future change must touch.

The method depends on an unusually tight feedback loop. Tests establish a baseline, tiny edits constrain the possible source of defects, and compilers or tools catch classes of mistakes. This is not a proof that behavior is unchanged. It is a practical risk-management strategy whose strength depends on test quality, runtime observability, and knowledge of external callers. Dynamic reflection, database migration, concurrency, and hard timing requirements make the safety boundary less predictable.

The book's object-oriented vocabulary reflects its 1999 setting, especially its emphasis on classes, inheritance, and polymorphism. The durable lesson is broader than any one design technique: isolate decisions likely to change, make intentions legible, and remove abstraction when it no longer earns its cost. Polymorphism is one answer to repeated variation, not the universal answer. Likewise, small methods help only when names and boundaries clarify the work rather than scattering it.

The most useful reading is therefore neither "clean everything" nor "never touch working code." Refactoring is disciplined maintenance in service of the next change. Its success is measured by whether the system becomes safer and cheaper to evolve, not by how elegant it looks in isolation.

Summary in 30 Seconds
Restructure code when a real change exposes costly complexity, then add the feature on a clearer foundation. Automated tests establish expected behavior, and tiny edits help pinpoint mistakes. Keep each responsibility near the information it uses, and treat duplicated logic or sprawling methods as clues to investigate, not automatic faults. Choose abstractions only when variation warrants them. Profile before optimizing, and limit repairs to changes you can verify.
Contains spoilers

Last updated:

Report Issue

Review Summary

4.24 out of 5
Average of 8k+ ratings from Goodreads and Amazon.

Refactoring is highly regarded as an essential read for software developers, offering practical techniques to improve code quality. Readers appreciate its clear explanations, JavaScript examples, and catalog of refactorings. Many find it useful as a reference guide throughout their careers. Some criticize outdated content in older editions and paper quality issues. While experienced developers may find less new information, most agree it's valuable for understanding and applying refactoring principles. The book emphasizes incremental changes, controlled processes, and adapting refactoring techniques to specific contexts.

Your rating:
4.59
405 ratings
Want to read the full book?

Glossary

Refactoring

Behavior-preserving restructuring

A change to software's internal structure intended to make it easier to understand and modify, while preserving its observable behavior. A refactoring is one such change, while to refactor is to apply a sequence of changes. The book distinguishes this work from adding features and from performance optimization because each has a different purpose.

Code Smells

Warning signs in code

Recurring structures that suggest a program may be difficult to understand or change. Examples include duplicated code, long methods, large classes, and conditionals repeated across a system. A smell does not prove a design is wrong; it directs a programmer to investigate whether a refactoring would reduce a concrete maintenance problem.

Two Hats

Separate coding intentions

A way to distinguish adding functionality from refactoring. While adding a feature, a developer changes what the program does. While refactoring, the developer changes its internal structure while preserving what it does. Switching deliberately between these activities makes progress and unintended behavior changes easier to recognize.

Rule of Three

Refactor repeated solutions

A guideline for deciding when repeated code may deserve consolidation. The first time a solution appears, implement it. When it appears a second time, recognize the duplication but do not automatically abstract it. When a similar case appears a third time, consider refactoring the repeated structure into a shared design.

Null Object

Polymorphic absence case

An object that represents the absence of an ordinary object while supporting the same interface. Instead of repeatedly checking for null, clients can ask the object to perform an operation, and the null version supplies a suitable default response, such as an empty collection or zero value. It is appropriate only when that default behavior is meaningful.

Replace Conditional with Polymorphism

Distribute type-based behavior

A refactoring that moves branches of a conditional based on an object's type into overriding methods on corresponding subclasses or state objects. Callers then make one common request, and the relevant implementation handles the variation. It is especially useful when the same type decision appears in several places, but can be excessive for a small, stable conditional.

Form Template Method

Share an algorithm's outline

A refactoring for similar methods in subclasses that perform steps in the same order but differ in some details. The common sequence is moved into a superclass method, while each differing step is given a consistent method signature and implemented by subclasses. The shared outline removes duplication without erasing the intended variations.

FAQ

What's Refactoring: Improving the Design of Existing Code by Martin Fowler about?

  • Focus on Code Improvement: The book is centered on refactoring, which involves restructuring existing code to enhance its internal structure without changing its external behavior.
  • Practical Techniques: It offers a catalog of over seventy refactorings, each with detailed instructions and examples, making it practical for developers to apply in real-world scenarios.
  • Target Audience: Aimed at professional programmers, it serves as a guide for improving coding practices and software design.

Why should I read Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Enhance Code Quality: The book provides insights into improving code design, making it easier to maintain and extend, which is crucial for long-term projects.
  • Learn Proven Techniques: It offers structured, real-world-tested refactoring techniques that can boost productivity and coding confidence.
  • Avoid Common Pitfalls: By identifying "bad smells" in code, it helps developers proactively refactor before issues become unmanageable.

What are the key takeaways of Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Refactoring is Essential: It is a necessary part of software development to prevent code decay and maintain design integrity.
  • Small Steps Matter: Advocates for incremental changes to minimize bugs and track changes easily.
  • Testing is Crucial: A robust suite of tests is essential to ensure consistent code behavior during refactoring.

How does Refactoring: Improving the Design of Existing Code by Martin Fowler define refactoring?

  • Definition of Refactoring: It is the process of changing a software system to improve its internal structure without altering its external behavior.
  • Purpose of Refactoring: Aims to make code easier to understand and modify, leading to better software quality.
  • Continuous Process: Refactoring should be integrated into regular development practices to maintain code quality over time.

What are "bad smells" in code as described in Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Indicators of Problems: "Bad smells" are symptoms in the code that suggest deeper issues, such as duplicated code or long methods.
  • Common Examples: Includes "Duplicated Code," "Long Method," and "Feature Envy," each indicating a need for refactoring.
  • Actionable Insights: Provides specific refactorings to address each type of bad smell, improving code clarity and maintainability.

What is the "Rule of Three" in Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Guideline for Refactoring: Suggests refactoring after the third instance of similar code to prevent duplication from becoming a larger issue.
  • Encourages Proactive Refactoring: Promotes maintaining clean and manageable code by being proactive about refactoring.
  • Practical Application: Helps developers reduce technical debt by maintaining a cleaner codebase.

What are some common refactorings mentioned in Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Extract Method: Involves creating a separate method from a section of code to improve readability and reusability.
  • Inline Method: Opposite of Extract Method, where a method's body is replaced with its calls to simplify the code.
  • Move Method: Used when a method is more relevant to another class, improving code organization and responsibilities.

How does testing play a role in refactoring according to Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Foundation for Refactoring: A solid suite of tests is essential to ensure consistent code behavior during refactoring.
  • Self-Testing Code: Advocates for writing self-testing code to automatically verify expected behavior after changes.
  • Continuous Testing: Encourages frequent testing to catch issues early, leading to more reliable and maintainable code.

What is the significance of "Encapsulate Field" in Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Improves Data Access: Involves creating getter and setter methods for a field to maintain data integrity.
  • Facilitates Future Changes: Allows changing the internal data representation without affecting external code.
  • Promotes Good Design Practices: Encapsulation is a fundamental principle of object-oriented design, reducing class coupling.

What are some best practices for refactoring as outlined in Refactoring: Improving the Design of Existing Code by Martin Fowler?

  • Take Small Steps: Emphasizes making small, incremental changes to minimize bugs and track changes easily.
  • Test Frequently: Run tests after each small change to ensure consistent code behavior and catch issues early.
  • Focus on Readability: Refactor to make code more understandable, leading to better maintainability and collaboration.

What are the best quotes from Refactoring: Improving the Design of Existing Code by Martin Fowler and what do they mean?

  • "Code is like humor. When you have to explain it, it’s bad.": Stresses the importance of writing clear, understandable code.
  • "Refactoring is a controlled technique for improving the design of an existing code base.": Highlights refactoring as a systematic approach to enhance code quality.
  • "The best time to refactor is when you are adding a feature.": Suggests integrating refactoring into the development process to maintain clean and efficient code.

How can I apply the concepts from Refactoring: Improving the Design of Existing Code by Martin Fowler in my projects?

  • Start Small: Begin with simple refactorings in current projects, focusing on one or two techniques at a time.
  • Incorporate Refactoring into Workflow: Make it a regular part of development, such as during code reviews or when adding features.
  • Encourage Team Collaboration: Share concepts and techniques with your team for better code quality and shared understanding.

About the Author

Martin Fowler is a renowned software engineer and thought leader in the field of enterprise software design. Born in 1963, he has made significant contributions to agile software development methodologies, including extreme programming. As Chief Scientist at ThoughtWorks, Fowler advocates for best practices in software development and has authored influential books on refactoring, domain-driven design, and enterprise application architecture. His work has shaped modern approaches to software design, emphasizing clean code, continuous integration, and adaptive planning. Fowler's ideas and writings continue to influence developers and organizations worldwide, promoting more efficient and effective software development processes.

Download PDF

To save this Refactoring summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.37 MB     Pages: 18

Download EPUB

To read this Refactoring summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 1.38 MB     Pages: 22
Want to read the full book?
Follow
Listen
Home
Swipe
Library
Get App
Try Full Access for 3 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
Read unlimited summaries. Free users get 3 per month
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
—
❤️ Unlimited Bookmarks
Free users are limited to 4
—
📜 Unlimited History
Free users are limited to 4
—
📥 Unlimited Downloads
Free users are limited to 1
—
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 26,000+ books. That's 12,000+ hours of audio!
Day 2: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 3: Your subscription begins
You'll be charged on Nov 24,
cancel anytime before.
Consume 2.8× More Books
2.8× more books Listening Reading
Our users love us
1M+ readers
Trustpilot Rating
TrustPilot
4.6 Excellent
This site is a total game-changer. I've been flying through book summaries like never before. Highly, highly recommend.
— Dave G
Worth my money and time, and really well made. I've never seen this quality of summaries on other websites. Very helpful!
— Em
Highly recommended!! Fantastic service. Perfect for those that want a little more than a teaser but not all the intricate details of a full audio book.
— Greg M
Save 62%
Yearly
$119.88 $44.99/year/yr
$3.75/mo
Monthly
$9.99/mo
Start a 3-Day Free Trial
3 days free, then $44.99/year. Cancel anytime.
Unlock a world of fiction & nonfiction books
26,000+ books for the price of 2 books
Read any book in 10 minutes
Discover new books like Tinder
Request any book if it's not summarized
Read more books than anyone you know
#1 app for book lovers
Lifelike & immersive summaries
30-day money-back guarantee
Download summaries in EPUBs or PDFs
Cancel anytime in a few clicks

Why one summary?

Scanner
Find a barcode to scan

⭐
⭐
⭐
We have a special gift for you
Open
38% off
DISCOUNT FOR YOU
⭐
⭐
⭐
$79.99
$49.99/year
Only $4.16 per month
Continue
2 taps to start, super easy to cancel
Settings
General
Widget
Loading...