About this book
Refactoring: Improving the Design of Existing Code was published by Addison-Wesley in 1999. Its author is Martin Fowler, with contributions from Kent Beck, John Brant, William Opdyke and Don Roberts. A second edition, substantially rewritten, appeared in 2018. The book gave a name, a definition and a working method to something good programmers had long done informally: improving the structure of code that already works, without changing what it does.
The problem it addresses is familiar to anyone who has worked on software for more than a few months. Code that starts clean becomes tangled as features are added, deadlines press and understanding shifts. Each change makes the next one a little harder. Eventually the team is afraid to touch the code at all. The usual responses are to live with the decay or to call for a complete rewrite, and both are expensive. Fowler's book offers a third path: improve the design continuously, in small steps so safe that the program never stops working.
The book defines refactoring as a change to the internal structure of software that makes it easier to understand and cheaper to modify, while leaving its observable behaviour unchanged. The word is used both as a noun, for a particular named change such as extracting a function, and as a verb, for the activity of applying a series of such changes. The key point in both senses is the separation of two activities: changing what the program does, and changing how it is organised. Refactoring is only the second.
The intended reader is a working programmer who maintains or extends code, which is to say nearly every programmer. The first edition used Java for its examples, reflecting the language's dominance in business software at the time. The second edition uses JavaScript, chosen as a widely read language that lets the examples be understood by programmers from many backgrounds. The ideas are not tied to either language.
The book is organised as a short introduction of principles followed by a long catalogue. It opens with a worked example that refactors a small program step by step. It then explains why and when to refactor, describes the signs that code needs refactoring, explains how to build the tests that make refactoring safe, and then presents dozens of individual refactorings in a uniform format. This study edition does not reproduce the example or the catalogue. It explains what the book is for, the ideas it rests on, where it came from, and how to read it well.
The author and his collaborators
Martin Fowler
Martin Fowler is a British software developer and writer who has spent most of his career in the United States. He began in the 1980s, worked as an independent consultant on object-oriented systems in the 1990s, and in 2000 joined ThoughtWorks, a software consultancy, where he became its chief scientist. He is known for clear writing about design and process. His other books include UML Distilled, a short and very popular guide to the Unified Modeling Language; Analysis Patterns, on modelling business domains; and Patterns of Enterprise Application Architecture, on the structure of business software. His long-running website, on which he publishes essays and a glossary of software terms he calls a bliki, has been one of the most widely read sources on software design for decades. He was among the authors of the Agile Manifesto in 2001.
Fowler describes himself as a writer who tries to capture and explain good practice he has seen, rather than an inventor of new techniques. That is a fair description of Refactoring. Its techniques were practised before the book; Fowler's contribution was to collect them, name them, describe each one's mechanics precisely, and explain the discipline that makes them safe.
The Smalltalk roots
The practice of refactoring grew up in the Smalltalk community of the 1980s and early 1990s. Smalltalk programmers worked in an environment where code could be changed and run immediately, and some of them, including Ward Cunningham and Kent Beck, developed a habit of continually reshaping their code as their understanding grew. Beck contributed the chapter on bad smells in the book and much of its spirit.
The academic foundation came from the University of Illinois at Urbana-Champaign. William Opdyke, a doctoral student working with Ralph Johnson, wrote a thesis in the early 1990s that defined a set of refactorings for object-oriented programs and analysed the conditions under which each one preserves behaviour. John Brant and Don Roberts, also at Illinois, built the Refactoring Browser, a Smalltalk tool that could perform many refactorings automatically and safely. All three contributed to the book. Fowler, who had seen refactoring practised by Beck and others, brought these threads together for a wide audience of programmers working in mainstream languages.
Two editions
The first edition appeared in 1999, at the same moment as Extreme Programming, which made refactoring one of its core practices. The second edition, nearly twenty years later, keeps the structure and philosophy but rewrites almost everything else. The opening example is new, many refactorings were renamed, merged, added or removed, and the presentation shifts from a strongly class-centred style toward one that treats functions and data as equally important, reflecting changes in how programs are written. The second edition also has a companion online catalogue.
What changed between them
Comparing the editions is instructive in itself. The first edition was written when class-based object-oriented programming was the dominant style, and many of its refactorings were phrased in terms of methods, fields and subclasses. By 2018, much code was written in languages and styles that mixed objects with plain functions, used functions as values, and treated data transformation as central. The second edition reflects this. Several refactorings were renamed to use the word function where the first edition said method. New refactorings were added for separating a computation into phases, for replacing loops with pipelines of operations over collections, and for dealing with mutable data and global variables. Some older refactorings that had become less useful were dropped from the main book.
The change of language from Java to JavaScript caused some debate. Fowler explained that he wanted examples readable by the widest range of programmers, and that he avoided language features that would confuse readers from other backgrounds. The examples deliberately use a plain style. A reader who works in another language should find them easy to translate, which is itself a sign that the techniques are general.
What did not change is equally telling. The definition of refactoring, the two hats, the insistence on tests, the emphasis on small steps, the smells and the catalogue format all survived intact. Twenty years of practice confirmed the core of the first edition and refined its details.
The shape of the argument
The book makes its case in a particular order, and the order is part of the argument. It does not begin with definitions. It begins by showing.
Show first
The opening chapter takes a small, working, but poorly organised program and improves it through many tiny steps. After each step the tests are run. The program's output never changes; its structure changes a great deal. By the end, the code is organised so that a new requirement, which would have been awkward to add at the start, becomes easy. The reader sees refactoring before being told what it is. The chapter's real lesson is less about any particular change than about the rhythm: change a little, test, change a little more, test again.
Then explain
Next comes a chapter of principles: what refactoring is, why programmers should do it, when to do it, when not to, how to explain it to managers, how it relates to performance and to design, and what problems it raises. Then comes the chapter on bad smells, which gives names to the symptoms that suggest code needs restructuring. Then a chapter on building tests, which explains why automated tests are the precondition for refactoring and how to write them.
Then catalogue
The rest of the book is the catalogue. Each refactoring is given a name, a short summary, a motivation explaining when and why to use it, mechanics describing the safe steps to carry it out, and an example. Many refactorings come in pairs that undo each other, such as extracting a function and inlining a function, because the right direction depends on the situation. The catalogue is grouped by theme: basic refactorings, encapsulation, moving features, organising data, simplifying conditional logic, refactoring interfaces, and dealing with inheritance.
The argument underneath
Beneath this structure lies a single claim. Design is not something done once at the start and then preserved. It is a property of code that must be maintained continuously, in the same way that a garden must be tended. Refactoring is the means of tending it. Tests make the tending safe. Smells tell you where to tend. Names make the work communicable. Small steps keep the risk low. Every part of the book serves this claim.
Idea one: structure and behaviour are separate
The foundation of the book is a distinction that seems simple but changes how a programmer works. Any change to code either alters what the program does, its behaviour, or alters how the program is organised, its structure. Refactoring changes only structure. Adding a feature or fixing a bug changes behaviour.
Of course many real changes involve both. The book's insistence is that they should not be done at the same time. When a programmer mixes them, every test failure becomes ambiguous: is it because the new feature is wrong, or because the restructuring broke something? When they are separated, each step has a clear standard of success. A refactoring step succeeds if every test still passes. A feature step succeeds if the new test passes and the old ones still do.
The two hats
Kent Beck's image for this, which the book adopts, is the two hats. When programming, you wear one hat at a time. With the adding-function hat on, you add new capabilities and the tests that check them, and you do not restructure. With the refactoring hat on, you restructure and add no new capabilities. You may swap hats often, perhaps every few minutes, but you should always know which one you are wearing. This simple discipline makes complex changes manageable.
An analogy
Think of rearranging a kitchen while also cooking dinner in it. If you try to move the spice rack, reorganise the drawers and cook a new recipe all at once, and the meal goes wrong, you will not know whether you used the wrong spice because you could not find the right one or because the recipe was poor. If instead you first rearrange, check that everything is findable, and then cook, each activity can be judged on its own terms.
What behaviour means
The definition depends on what counts as observable behaviour. In practice it means behaviour that matters to users of the code: outputs, side effects and responses to inputs. Refactoring may change things that are not part of this, such as the internal call sequence, memory use or speed. A refactoring that makes code slower has still preserved behaviour in the book's sense, though the book has a section on how to handle performance separately. Where code is a public interface used by others, the boundary of behaviour expands to include its exact signatures, and refactoring must take more care.
Where it leads
The separation of structure and behaviour has consequences beyond individual sessions at the keyboard. In version control, it suggests keeping refactoring commits separate from feature commits, so that reviewers can check each kind on its own terms: a refactoring commit should change no tests and alter no outputs, while a feature commit should be small because the ground has already been prepared. In code review, it lets a reviewer read a large structural change quickly, trusting the tests, and spend attention on the smaller behavioural change that follows. In planning, it helps a team see that much of the cost of a feature lies in preparing the code to receive it, and that this preparation is legitimate work.
It also changes how a programmer feels about existing code. Code that seemed fixed and fragile becomes material that can be reshaped. That shift in attitude, from fear of change to confident, careful change, may be the book's most important effect on the people who read it. A team that has absorbed it no longer says that a part of the system cannot be touched. It says that the part needs tests first, and then it can be improved step by step.
Idea two: small steps, always working
The second central idea is that refactoring proceeds in very small steps, each of which leaves the code working. This is what distinguishes refactoring from restructuring in general. A programmer who spends three days rearranging code, with the program broken throughout, and then tries to get it working again, is not refactoring in Fowler's sense, even if the end result is the same.
Each refactoring in the catalogue is broken down into mechanics: a sequence of steps, each small enough to check. To move a function from one module to another, for example, one might copy it to the new location, adjust it to fit, make the old one delegate to the new one, run the tests, then change callers one by one, testing as you go, and finally remove the old function. At no point is the program broken for more than a moment.
Why small steps are faster
It seems natural to think that small steps are slower than large ones. The book argues the reverse. Large changes produce large failures, and finding the cause of a failure in a large change can take far longer than making the change. Small steps fail rarely, and when they do, the cause is obvious: it is in the last few lines changed. Undoing is trivial. Over a day's work, the programmer who takes small steps usually finishes sooner and with more confidence. Many readers report that this was the most surprising and lasting lesson they took from the book.
Composing big changes from small ones
Small steps can add up to large transformations. A tangled module can be split, an inheritance hierarchy replaced with delegation, or a central data structure changed, all through a long sequence of tiny safe steps. Because the program works after every step, the work can be paused at any point, merged with others' changes, or abandoned without loss. This makes refactoring compatible with team work and with continuous delivery of software, where the code must always be ready to release.
What it is confused with
The word refactoring is often used loosely to mean any rewriting or cleanup, including large redesigns that break the code for weeks. Fowler has written that when someone says the system is broken for a few days because they are refactoring, they are not refactoring. The precise meaning matters, because the safety comes from the discipline, not from the intention to improve.
Idea three: tests make it safe
Refactoring depends on knowing that behaviour has not changed. The only practical way to know this is to run a good suite of automated tests after each step. The book therefore devotes a whole chapter to tests, and treats self-testing code, code that comes with tests able to check it automatically, as the precondition of refactoring.
What good tests look like here
For refactoring, tests must be fast, because they will be run many times an hour. They must be automatic, reporting success or failure without a person inspecting output. They must be reliable, so that a failure means a real problem. And they must cover the behaviour that matters. The book recommends focusing tests on areas where bugs are likely, on boundary conditions, and on cases where things go wrong, rather than aiming for an abstract coverage figure.
Tests as a safety net and a design aid
A useful image is the safety net under a trapeze. With the net in place, the performer can attempt moves that would be reckless without it. With a good test suite, a programmer can make structural changes that would otherwise be too frightening to try. The book also notes that writing tests changes how code is designed. Code that is easy to test tends to have clear inputs and outputs and few hidden dependencies, which are also signs of good structure.
When there are no tests
Much real code has no tests. The book acknowledges this and recommends adding tests before refactoring, at least around the area to be changed. How to do that in code never designed for testing is a hard problem in its own right, and Michael Feathers' Working Effectively with Legacy Code, on this shelf, is devoted to it. Fowler's book also notes that some simple refactorings, performed by reliable automated tools, can be done safely even with weak tests, which can be a way to start.
Where it leads
The close link between refactoring and testing helped spread automated testing across the industry. It also underlies the practice of test-driven development, associated with Kent Beck, in which the cycle is to write a failing test, make it pass in the simplest way, and then refactor. Refactoring is the third step of that cycle, the step that keeps the design clean as features accumulate.
Idea four: code smells
If refactoring is the remedy, how does a programmer know where to apply it? The book's answer, developed in a chapter written with Kent Beck, is the idea of code smells. A smell is a surface sign that something in the design may be wrong. It is not a rule that something is wrong; it is a prompt to look more closely, the way an odd smell in a kitchen prompts a look in the refrigerator.
The authors deliberately chose a vague, sensory word. They argue that no precise metric can tell a programmer when a function is too long or a class too large. Experienced programmers develop a feel for these things, and naming the common smells helps others develop that feel faster. Each smell in the chapter is paired with the refactorings most likely to help.
Some common smells
Duplicated code is the most basic: the same logic in more than one place means every change must be made more than once. Long functions are hard to understand, and the book argues that the right response is usually to break them into smaller functions with names that explain what each part does. Large classes or modules try to do too much and become dumping grounds. Long parameter lists make functions hard to call and hint that some parameters belong together in an object of their own.
Some smells are about how change spreads. Divergent change is when one module is changed for many different reasons, suggesting it should be split. Shotgun surgery is the opposite: one logical change requires small edits in many modules, suggesting related things should be gathered together. Feature envy is when a function seems more interested in another module's data than its own, and probably belongs there. Data clumps are groups of values that always travel together and deserve to become a single structure. Primitive obsession is the habit of using basic types, such as strings and numbers, for concepts that deserve their own types, such as money, date ranges or telephone numbers.
Other smells concern unnecessary structure. Speculative generality is flexibility added for a future that never came. Middle men are classes that do nothing but pass requests on. Long message chains, where code navigates through a series of objects to reach the one it needs, tie the caller to the whole path. The second edition adds smells reflecting newer concerns, among them unclear names, global data and mutable data, which make programs hard to reason about.
Comments as a smell
One smell surprises many readers: comments. The book does not say comments are bad. It says that when a block of code needs a long comment to explain what it does, the code itself could often be made clearer, for example by extracting the block into a function whose name says what the comment said. Comments explaining why something is done, or what is not yet known, remain valuable. The point is that a comment is sometimes a deodorant covering a smell rather than a cure for it.
Why the idea matters
Smells give programmers a shared vocabulary for code review and for their own judgement. Saying that a function has feature envy, or that a change is shotgun surgery, communicates a specific concern and suggests a specific remedy. The list has been widely copied, extended and built into automated code analysis tools. Its deeper lesson is that design quality can be perceived, discussed and improved locally, without first producing a complete theory of what good design is.
Smells as judgement, not rules
It is worth stressing what the smell chapter does not do. It does not give thresholds, such as a maximum number of lines per function or parameters per call. Teams that turn smells into rigid rules, enforced by tools without discussion, often produce code that satisfies the rule and misses the point, for example by splitting a clear function into fragments merely to meet a line limit. The authors intended smells as prompts for a trained eye. A smell is a reason to look, think and perhaps act, and sometimes the right conclusion after looking is that the code is fine as it is. Tools that flag smells are useful assistants, but the decision to refactor belongs to a person who understands the code, the change about to be made, and the cost of the work. The chapter trains that person's eye; it does not replace it, and it was never meant to be read as a checklist.
Idea five: named refactorings with exact mechanics
The bulk of the book is a catalogue of refactorings, each with a name. This naming does for structural change what the Design Patterns book did for structure itself. Before the book, programmers might say they had cleaned up a function. After it, they could say they had extracted a function, introduced a parameter object, replaced a conditional with polymorphism, or split a phase. Each name refers to a precise transformation with known steps and known effects.
Why names matter
Names allow programmers to talk about changes concisely, in conversation, code review and version-control messages. They allow tools to offer refactorings as commands. And they allow a programmer to think in larger units: instead of planning a hundred edits, one can plan a dozen named refactorings, each of which is known to be safe if performed according to its mechanics.
Mechanics as recipes for safety
The mechanics section of each entry lists the steps for performing the refactoring safely, with points at which to run tests. These steps are deliberately cautious. An experienced programmer may combine several when confident, and drop back to the smallest steps when something goes wrong. The book makes this explicit: the size of the steps should match the programmer's confidence, and when tests fail unexpectedly, the right response is to undo and take smaller steps.
Pairs and directions
Many refactorings come in opposing pairs. A function can be extracted or inlined; a variable can be extracted or inlined; a field can be moved one way or the other; a class can be split or merged. This reflects a central truth of the book: there is no single direction of improvement. The right structure depends on the current code and the change about to be made. Extracting a function helps when a block of code needs a name; inlining helps when a function's body is as clear as its name and the indirection adds nothing. The catalogue gives tools, not a direction.
An example in words
Consider a function that computes a shipping charge and contains a long conditional deciding between domestic and international rules. A programmer might first extract the domestic calculation into its own function, test, then extract the international calculation, test, then look at the remaining conditional and decide whether it reads clearly enough or whether the two cases should become two kinds of shipment object chosen once. Each of those moves is a named refactoring. Together they turn an opaque function into a readable design, without the program ever producing a different charge.
Idea six: when to refactor
A practical question for any team is when to spend time on refactoring. The book's answer is that refactoring should mostly be woven into everyday work, not scheduled as a separate project.
The rule of three
The book passes on a simple guideline, attributed to Don Roberts. The first time you do something, just do it. The second time you do something similar, notice the duplication but go ahead. The third time, refactor. This avoids premature abstraction, which guesses at structure before there is enough evidence, while still catching real duplication before it spreads.
Preparatory refactoring
The most valuable time to refactor, the book argues, is just before adding a feature. If the existing structure makes the new feature awkward, first refactor the code so that the feature fits naturally, then add it. The refactoring is justified by the feature it enables. Fowler uses the image of a journey: if the direct road is blocked, it may be faster to drive a little way to the highway than to push through side streets. Kent Beck's well-known formulation of this idea, roughly that one should first make the change easy and then make the easy change, captures the spirit.
Comprehension and litter-pickup
The second edition names other moments. Comprehension refactoring happens when a programmer has to understand code: as understanding grows, they rename variables and extract functions to put that understanding into the code itself, so the next reader does not have to rebuild it. Litter-pickup refactoring happens when a programmer passing through notices something poorly structured and improves it a little, like a walker picking up litter, leaving the code better than they found it. When a fix is too large to do in passing, they note it to come back to.
Planned and long-term refactoring
The book accepts that sometimes a team must plan a larger refactoring, for example to replace a library or restructure a core module. Even then, it recommends doing the work in small, safe increments alongside feature work, rather than stopping all feature work for a long cleanup. A team that needs frequent large planned refactorings has probably been neglecting the everyday kind.
When not to refactor
The book is also clear about when not to refactor. If code works and nobody needs to change or understand it, leave it alone, however ugly. If it would genuinely be easier to rewrite than to refactor, rewrite, though the book warns that this judgement is often made too readily. And refactoring has to be balanced against delivering value; it is a means to faster, safer change, not an end in itself.
Idea seven: design is continuous
Behind the practice lies a view of design that challenged the dominant thinking of the 1990s. The traditional view held that design should be done carefully up front, recorded in diagrams and documents, and then implemented. Changes to design during implementation were seen as failures of the design phase. Fowler's book suggests a different balance.
Design as a living property
If code can be restructured cheaply and safely, then the design need not be perfect at the start. It can begin simple, fitting the features currently needed, and evolve as new features reveal what structure is truly required. This is not the absence of design. It is design spread across the life of the project, with each decision made when the most information is available. The book calls the alternative, building flexibility for imagined future needs, speculative generality, and lists it as a smell.
An analogy
A town planner can design an entire city on paper before anyone lives there, or can lay out the main roads and let the city grow, adjusting streets and zoning as people's actual needs become clear. The first approach produces elegant plans that often fail to fit real life. The second produces cities that work, provided someone keeps tending them. Refactoring is the tending.
Not no design
The book is careful here. Fowler does not argue against thinking about design in advance. He argues that refactoring changes the balance: with a reliable way to change design later, less needs to be decided early, and early decisions can be simpler. Some decisions, such as public interfaces used by other teams or the shape of persistent data, remain expensive to change and deserve more forethought. The point is to move design effort to where it pays, not to abolish it.
Where it leads
This view became a foundation of agile development. Extreme Programming's practices of simple design and continuous refactoring depend on it. So does the broader idea of evolutionary architecture, in which large-scale structure is also expected to change over time, supported by tests and automation. And it underlies the modern expectation that a codebase is never finished but is a living thing maintained by a team.
Idea eight: the economics of refactoring
Refactoring takes time, and that time does not produce new features. Programmers often struggle to justify it to managers, and some feel guilty doing it at all. The book addresses this directly with an economic argument.
Speed comes from good design
The argument is that good design is what lets a team keep moving fast. In a well-structured codebase, a new feature can be added quickly because the code is easy to understand and the change fits somewhere natural. In a decayed codebase, every feature takes longer than the last, because programmers must understand tangled code, work around past decisions and fix unexpected breakages. Refactoring is how a team keeps the first situation from sliding into the second. Fowler later expressed this as a hypothesis about design stamina: investing in internal quality pays off after a surprisingly short time, perhaps weeks rather than years.
Talking to managers
The book's advice on managers is pragmatic. Many managers care about schedules, not structure. If refactoring is woven into feature work, as preparation for each change, then it is part of how features are delivered, and a programmer need not ask separate permission for it, just as a builder does not ask permission to measure before cutting. Where managers understand the link between design and speed, the conversation is easier. Fowler's later writing on technical debt, a metaphor coined by Ward Cunningham for the extra cost that poor structure imposes on future change, gives teams a vocabulary for this discussion.
What it is confused with
Refactoring is sometimes treated as gold-plating, polishing code for its own sake. The book's position is the opposite: refactoring is justified only by the future changes it makes cheaper. Code that will never change does not need refactoring. This economic framing keeps refactoring honest and prevents it from becoming a hobby that delays useful work.
Idea nine: performance and refactoring
A common objection to refactoring is that it makes programs slower. Extracting many small functions adds calls; replacing a single loop that does several things with several loops that each do one thing repeats work. The book takes this concern seriously and gives a clear answer.
Make it clear, then make it fast
Most of a program's running time is spent in a small fraction of its code. Programmers are notoriously bad at guessing which fraction, so optimising by intuition usually wastes effort on code that does not matter, while making that code harder to understand. The book recommends writing well-structured code first, then measuring performance with a profiler, and then optimising only the parts that measurement shows to be slow. Well-factored code makes this easier, because the slow parts are isolated in small functions that can be tuned without disturbing the rest.
An example
Suppose a report generator is slow. A programmer who has kept the code well factored can run a profiler, discover that nearly all the time is spent formatting dates, and optimise that single small function. A programmer working with one enormous tangled function would struggle even to find the hotspot, and any optimisation would risk breaking unrelated logic. Clarity first is not opposed to speed; it is usually the route to it.
Limits
The book does not claim performance never matters during design. Some systems have hard real-time requirements, and some choices of algorithm or data structure have performance consequences too large to fix later. But for most business and application software, the advice holds: structure for clarity and change, then measure and tune.
Idea ten: tools and the limits of refactoring
Automated refactoring
The Refactoring Browser had already shown that tools could perform refactorings safely. After the book appeared, mainstream development environments, first for Java and then for other languages, built in automated refactorings such as renaming, extracting functions and moving members. Today a programmer can rename a function across a large codebase with a single command, confident that every reference is updated. This automation changed everyday programming. Small refactorings that once took minutes and carried risk now take seconds and carry almost none, which makes the habit of continuous improvement far easier to sustain.
Where automation cannot reach
Tools are best at refactorings whose safety can be checked mechanically, typically in statically typed languages. In dynamic languages, or where code is called through reflection or from outside the program, tools can be less certain, and the programmer must rely more on tests. Larger refactorings that involve judgement, such as deciding how to split a module, still require a person. The book's mechanics remain useful here as the manual procedure behind what tools automate.
Published interfaces
The book identifies limits to refactoring. When code is used by others outside the team, its interface is published, and changing it may break code the team cannot see or change. In such cases the book recommends keeping the old interface working alongside the new one, deprecating the old, and removing it only when all users have moved. This idea later grew into practices often called parallel change or expand and contract.
Databases and shared data
Refactoring code that depends on a database is harder, because the data outlives any version of the program. The book acknowledges this; later work, notably on refactoring databases and on evolutionary database design, developed techniques for changing schemas in small, safe steps with migration scripts under version control.
Branches and teams
Finally, refactoring interacts with how teams share code. Long-lived branches make refactoring painful, because a rename or move on one branch conflicts with edits on another. The second edition argues for integrating changes into a shared main line frequently, at least daily, so that refactorings spread quickly and conflicts stay small. This links refactoring to continuous integration, a practice the book's community helped promote.
Idea eleven: refactoring as a way of understanding
Refactoring is usually described as a way of improving code. It is equally a way of understanding code. This side of the practice is easy to overlook, and it is one of the most useful.
Putting understanding into the code
When a programmer reads unfamiliar code, they build a mental model of it: this variable holds the running total, this block handles the discount, this loop is really searching for the first overdue item. Normally that model evaporates when the programmer moves on, and the next reader must build it again. Refactoring lets the model be written into the code. The variable is renamed to say what it holds. The block becomes a function named for the discount. The loop is replaced with a call whose name says it finds the first overdue item. The understanding is no longer in one person's head; it is in the code, available to everyone.
Learning by changing
The act of refactoring also deepens understanding. Code that seems obscure when read often becomes clear when one tries to restructure it, because each step forces a question: what does this part depend on, what does it produce, can it be moved? Fowler describes refactoring code he did not understand and finding that, after a series of small extractions and renames, the design became visible, sometimes revealing bugs that had been hidden by the clutter. Some programmers refactor unfamiliar code purely to understand it, then throw away the changes. Even then the exercise pays.
An analogy
Think of a student who rewrites dense lecture notes into their own outline, with headings, short summaries and a few diagrams. The content is the same, but the act of reorganising forces understanding, and the result is easier to review. Refactoring does the same for code, with the added benefit that the result is shared with the whole team.
Where it leads
This view connects refactoring to good naming, to readable code and to domain modelling. Evans' Domain-Driven Design, on this shelf, describes how a team's growing understanding of a business should be continually reflected in the code's structure and vocabulary, a process he calls refactoring toward deeper insight. Fowler's book supplies the small-scale technique that makes such large-scale evolution possible.
Refactoring beyond code
Although the book is about software, its core method generalises. The method has three parts: keep a clear test of whether the essential function is preserved, change structure in small steps, and check after each step. Many kinds of work can benefit.
A long document can be refactored. Its meaning is the behaviour to preserve; its structure, the order of sections, the grouping of ideas, the headings, can be improved step by step, rereading after each change to make sure nothing important was lost or distorted. A spreadsheet model can be refactored, with a set of known inputs and outputs acting as tests, while repeated formulas are gathered into one place and tangled sheets are separated. A business process can be refactored, keeping the outcome for customers fixed while reorganising who does what, one change at a time, with measurements taken after each.
In each case, the discipline protects against two common failures. One is never changing anything because change feels risky, so that structures decay. The other is changing everything at once, so that when something breaks nobody knows why. The middle path, steady improvement in small verified steps, is what the book teaches, and it is useful well beyond programming.
Reading the opening example
The opening chapter is the part of the book most worth reading slowly, and the part most often skimmed. In the first edition it concerns a small program for a video rental shop that prints a customer's statement. In the second edition it concerns a program that prints invoices for a theatre company. In both, the program works, but its main function is long, mixes calculation with formatting, and would be awkward to extend. A new requirement arrives, such as producing the statement in a different format, and the question is how to make room for it.
What to watch
The reader should watch the size of each step. Fowler changes very little at a time, often only a line or a name, and runs the tests after each change. He repeatedly pauses to ask whether the code now reads better. He removes temporary variables, extracts calculations into named functions, moves logic to where its data lives, and eventually separates the calculation of results from their presentation, so that a second presentation format becomes easy. He also shows small mistakes and how the tests catch them.
What the example is not
The example is not a model of ideal final code. Readers sometimes argue about whether the end result is better than some alternative, or whether the program was really bad enough to need all that work. These arguments miss the point. The example demonstrates a process: how to move from one structure to another, safely, with each step justified. Any programmer can follow the process toward whatever structure their situation needs.
An exercise
The best way to read the example is to type it. Set up the starting code and its tests in your own environment, then perform each step yourself, running the tests every time. It takes an evening or two. Many programmers who have done this say it changed their sense of what small means. They had thought of a small change as an hour's work. After the exercise they think of it as a minute's.
The tradition around it
Before the book
The idea that programs should be improved in structure, not only in function, goes back at least to the structured programming movement of the 1960s and 1970s. The Elements of Programming Style by Brian Kernighan and P. J. Plauger, on this shelf, showed small programs being rewritten for clarity, which is refactoring in spirit if not in name. Algorithms + Data Structures = Programs by Niklaus Wirth, also here, taught stepwise refinement, the gradual development of a program from an abstract outline to concrete code; refactoring can be seen as stepwise refinement applied to code that already exists. The direct roots, as described earlier, were in the Smalltalk community and in Opdyke's thesis at Illinois.
Alongside it
Refactoring appeared in the same year as Kent Beck's Extreme Programming Explained and Hunt and Thomas's The Pragmatic Programmer, both on this shelf. The three books reinforce each other. Extreme Programming made refactoring a core team practice, paired with test-first development and simple design. The Pragmatic Programmer urged programmers to fix broken windows and avoid duplication, and refactoring gave them the technique. Design Patterns by Gamma and colleagues, published five years earlier and also here, described target structures; refactoring showed how to reach them gradually. Joshua Kerievsky later wrote Refactoring to Patterns, which made that connection explicit.
After it
Working Effectively with Legacy Code by Michael Feathers, on this shelf, took up the hardest case: refactoring code that has no tests and was never designed to be tested. Feathers defined legacy code, provocatively, as code without tests, and gave techniques for breaking dependencies so tests could be added. Clean Code by Robert C. Martin, also here, describes the kind of code refactoring aims toward, with many of the same values. Domain-Driven Design by Eric Evans describes refactoring toward deeper insight, in which a team's growing understanding of the business is continually built into the model and the code. A Philosophy of Software Design by John Ousterhout offers a thoughtful challenge to some refactoring habits, arguing that splitting code into many very small functions can increase complexity by creating shallow modules with many interfaces. Reading Ousterhout and Fowler together is an excellent education in design judgement.
More broadly, the practice of refactoring is now built into nearly every development environment, taught in most software courses, and assumed by modern practices such as continuous integration and continuous delivery. The word itself has passed into general use, sometimes losing its precise meaning along the way.
Questions and criticisms
Small functions and indirection
The most persistent criticism concerns the book's preference for many small, well-named functions. Critics argue that code broken into many tiny pieces can be harder to follow, because the reader must jump between functions to understand a single flow. Ousterhout's book on this shelf makes a version of this argument. Fowler's position is that good names make jumping unnecessary: if a function's name says what it does, the reader need not look inside. Both views have merit. The practical lesson is that extraction helps when the new function has a meaningful name and a coherent purpose, and harms when it merely moves lines around.
Tests as a hard precondition
A second criticism is that the book's insistence on a good test suite makes it less useful for the code that most needs help: old code without tests. The book acknowledges this, and Feathers' later book addresses it. Meanwhile, automated refactoring tools reduce the risk for many simple changes even where tests are thin.
Misuse of the word
A third concern is cultural. The word refactoring is widely used for any kind of rewriting, including large risky changes that break code for long periods. This dilutes the idea and can give refactoring a bad name with managers, who hear it as a request for time that produces nothing. Fowler has written repeatedly about the precise meaning, but usage has drifted.
The object-oriented focus
The first edition was strongly oriented toward class-based object-oriented design, and some refactorings, especially those dealing with inheritance, felt specific to that style. The second edition broadened the presentation to treat functions and data more evenly. Programmers in functional languages have developed their own refactoring vocabularies, some of which overlap with Fowler's and some of which do not. The core ideas, separating structure from behaviour and moving in small tested steps, transfer to any paradigm.
Evolution versus design
Some critics argue that continuous refactoring can become a substitute for thinking about design, producing systems that are locally tidy but globally incoherent. This is a fair warning. Refactoring improves design within the frame of what the programmer understands; it does not supply understanding. Large architectural decisions still need deliberate thought, and the book does not claim otherwise.
What has held up
The central ideas have held up remarkably well. The separation of structure and behaviour is now basic professional knowledge. Small, tested steps are recognised as the safest way to change code. The smell vocabulary is used in code reviews and built into analysis tools. Automated refactoring is everywhere. And the view that design is maintained continuously, rather than fixed at the start, has become the default in most of the industry. With AI assistants now generating and modifying large amounts of code, the discipline of changing structure only under the protection of tests, in steps small enough to verify, is if anything more valuable than before.
Why it is on this shelf
This shelf gathers books that teach durable habits of thought. Refactoring is here because it teaches one of the most useful habits in any kind of making: improve the structure of a thing in small, checked steps while it continues to work. That habit applies to code, but also to documents, organisations, arguments and plans.
For a reader of Vedanta, Jyotish, science and economics, the book offers a clear example of a method that separates what something does from how it is arranged, and keeps the first constant while improving the second. Good commentary traditions work this way: a teaching is restated and reorganised over centuries, but its meaning is kept. Good scientific theories are reformulated into clearer and more general forms while still predicting the same observations. In economics, institutions are reformed most safely when each change is small enough for its effects to be seen before the next is made.
For technology, it is here because most real software work is changing code that already exists, and this is the book that explains how to do that well. It also gives a precise vocabulary, used daily by programmers and built into their tools, that makes design discussions concrete.
Finally, it is here because it models a temperament: patient, careful, unafraid of change but unwilling to take reckless risks. That temperament is worth cultivating anywhere.
How to read it
Choose the edition
Choose the edition whose language you read most comfortably. The second edition, in JavaScript, is more current in style and treats functions and data more evenly; most readers should start there. The first edition, in Java, remains valuable, especially for programmers working in class-heavy object-oriented code, and its catalogue differs in places. Either edition teaches the essentials.
First pass
Read the opening example first, and work through it at the keyboard as suggested above. Then read the chapter on principles, which explains why and when to refactor; mark the passages about preparatory refactoring, the two hats, performance and when not to refactor. Then read the chapter on bad smells in full, ideally more than once. Then the chapter on tests. These four chapters are the heart of the book and can be read in a week or two of evenings.
The catalogue
Do not read the catalogue from start to finish on the first pass. Start with the most basic refactorings: extracting and inlining functions and variables, renaming, changing function declarations, and introducing parameter objects. Learn these until they are automatic, ideally using your environment's automated support. Then, whenever you meet a particular smell in your work, look up the refactorings the smell chapter suggests and read their motivation and mechanics. Over months the catalogue becomes familiar through use.
Pencil work
Two kinds of pencil work help. First, for the smells chapter, write next to each smell an example from code you know. Second, for any refactoring you study, write out its mechanics in your own words as a numbered list, then perform it on real code, noting where you were tempted to take a larger step. Comparing your own steps with Fowler's is a good way to calibrate.
Pace and practice
Practice matters more than reading. Set a small goal each day: one rename that makes a name clearer, one function extracted from a long one, one duplication removed, each under test. After a few weeks, the habit of leaving code a little better than you found it becomes natural.
What to read next
From this shelf, read Working Effectively with Legacy Code by Michael Feathers next, for the case where tests are missing. Then Design Patterns by Gamma, Helm, Johnson and Vlissides, to learn the structures that refactoring often moves toward. Extreme Programming Explained by Kent Beck shows refactoring in its original team setting. A Philosophy of Software Design by John Ousterhout offers a thoughtful counterpoint on how small modules should be. Domain-Driven Design by Eric Evans shows refactoring applied to the model of a business, not only to code.
Questions to carry
- Am I wearing the refactoring hat or the feature hat right now?
- If my tests pass after this change, how sure am I that behaviour is unchanged?
- Is this step small enough that, if the tests fail, I will know immediately why?
- Which smell am I noticing in this code, and which refactorings address it?
- Would this new feature be easier to add if I first changed the structure of the code?
- Is this comment explaining why, or covering up code that could explain itself?
- Does this function have a name that would let a reader skip its body?
- Am I adding flexibility for a need that exists, or for one I am only imagining?
- Who else depends on this interface, and how can I change it without breaking them?
- Have I measured where this program is slow, or am I guessing?
- Is this code worth refactoring at all, given how often it will change?
- How long has the main line of code been broken during my current work?
- What did I learn about this code today, and have I put that understanding into the code itself?
Words to know
- Refactoring (noun): A named change to code's internal structure that leaves its observable behaviour unchanged.
- Refactoring (verb): Restructuring code by applying a series of such behaviour-preserving changes.
- Observable behaviour: What a program does as seen by its users or callers, as opposed to how it is organised inside.
- Two hats: The discipline of either adding function or refactoring at any moment, never both at once.
- Mechanics: The step-by-step procedure for performing a refactoring safely.
- Self-testing code: Code accompanied by automated tests able to check its behaviour quickly.
- Code smell: A surface sign in code that suggests a deeper design problem worth investigating.
- Duplicated code: The same logic appearing in more than one place, so that changes must be repeated.
- Feature envy: A function that uses another module's data more than its own and probably belongs elsewhere.
- Shotgun surgery: A single logical change that requires small edits in many places.
- Divergent change: A single module that is changed for many unrelated reasons.
- Primitive obsession: Using basic types like strings and numbers for concepts that deserve their own types.
- Speculative generality: Flexibility or abstraction added for imagined future needs that have not arrived.
- Extract function: Turning a fragment of code into its own named function.
- Inline function: Replacing calls to a function with its body when the indirection adds nothing.
- Rule of three: Refactor duplication on the third occurrence rather than the first or second.
- Preparatory refactoring: Restructuring code just before adding a feature so that the feature fits easily.
- Technical debt: Ward Cunningham's metaphor for the extra cost that poor internal structure imposes on future changes.
- Published interface: An interface used by code outside the team's control, which must be changed with special care.
- Parallel change: Introducing a new interface alongside the old, migrating users, then removing the old.
- Profiler: A tool that measures where a program spends its time, used to target optimisation.
- Refactoring Browser: An early Smalltalk tool, built at the University of Illinois, that performed refactorings automatically.
- Legacy code: Old code still in use; in Michael Feathers' sense, code without tests.
A note on this edition
This is a study edition written for this shelf in our own words. It explains what refactoring is, where the idea came from, the principles the book rests on, how it has been received, and how to read it. It does not reproduce the book's worked example, its smells chapter or its catalogue, and it cannot replace them.
Refactoring: Improving the Design of Existing Code is in copyright and remains in print in its second edition. It is worth getting from a library or a bookshop, and it is the kind of book best kept near the keyboard, opened whenever a smell appears in real code.