About this book
Working Effectively with Legacy Code was published by Prentice Hall in 2004, as part of a series of books edited by Robert C. Martin. Its author, Michael Feathers, wrote it for a reader most programming books ignore: the developer who did not write the code in front of them, does not fully understand it, and must change it anyway, usually by a deadline. That developer is the normal case in the industry. Most programming work is done on existing systems, not on fresh ones.
The book opens with a definition that has become famous. Legacy code, for Feathers, is simply code without tests. The age of the code does not matter. Whether it is well designed does not matter. Whether the original author is still around does not matter. If there are no tests that tell you whether a change has broken something, the code is legacy code, and changing it is a gamble. By this definition, code written last week can be legacy code, and a twenty-year-old system with a thorough test suite is not.
The definition is provocative on purpose. It moves attention away from blame and nostalgia, the usual tone of conversations about old systems, and towards a concrete, fixable property. You cannot easily make old code young or ugly code beautiful. You can, with work, get it under test. Once it is under test, you can change it with confidence, and once you can change it with confidence, you can improve its design a little at a time.
The problem the book addresses is a trap. To change code safely you need tests. To add tests you usually need to change the code, because legacy code is typically full of dependencies that make it impossible to run a piece of it in isolation. A class creates a database connection in its constructor. A function calls a global object that talks to a hardware device. A method is two thousand lines long and does twelve things. You cannot test it without changing it, and you cannot change it safely without testing it.
Feathers's answer is a set of techniques for breaking out of this trap with as little risk as possible. The early changes, made before tests exist, are small, mechanical and conservative, chosen because they are very unlikely to break anything. They loosen just enough of the code's dependencies to let a test harness reach the part that needs to change. Then tests go in. Then the real change is made, under the protection of the tests. Over many such changes, the tested area of the system grows, and the code becomes easier to work with.
The book was written at a particular moment. Extreme Programming and test-driven development had made automated unit testing fashionable, and tools such as JUnit were widely used. But most of the advice about testing assumed that one was writing new code, designed from the start to be testable. Programmers who tried to apply these ideas to existing systems found that the advice did not fit. Feathers, who had spent years helping teams in exactly this situation, wrote the book that filled the gap.
The author
Michael Feathers worked for many years as a consultant with Object Mentor, the firm associated with Robert C. Martin, which trained and coached teams in object-oriented design and agile methods. His work took him into many organisations with large, old, poorly tested codebases, in languages from C and C++ to Java and C#. The book reads like the distillation of that fieldwork. Its examples are fictionalised and simplified, but they have the texture of real systems: odd global variables, classes that do too much, methods that nobody dares touch.
Feathers was active in the early unit-testing community. He worked on testing tools for C++, a language in which testing was then especially awkward, and his interest in seams, the places where behaviour can be changed without editing code, shows the habits of someone who has had to test C and C++ code where there are no convenient object interfaces to work with. He is also often credited with coining the acronym that groups Robert Martin's five principles of object-oriented class design, a small sign of how closely he worked within that circle.
After the book, Feathers continued as a consultant and speaker, with a growing interest in how code changes over time and what the history of a codebase reveals about its design. He has written and spoken about using version control history to find the parts of a system that change most often, which are usually the parts that most reward attention. That interest is already visible in this book, which treats a codebase as something with a past and a trajectory, not as a static design.
What makes Feathers distinctive among writers on software is his tone. He is patient, practical and unjudgemental. He does not mock the authors of the code he describes. He knows that bad code is usually written by competent people under bad conditions, and that the person reading his book is likely tired, behind schedule and anxious. The final chapter of the book speaks directly to the morale of teams who feel overwhelmed by their code, which few technical books ever do.
The shape of the argument
The book has three parts, and they serve different purposes. The first part is a short conceptual foundation. The second is a long collection of problem-oriented chapters. The third is a reference catalogue of techniques. A reader should know from the start that the book is not meant to be read only once, from front to back. It is built to be consulted.
The first part explains why changing software is hard and what makes it safe. It introduces the reasons for change, such as adding a feature, fixing a bug, improving design and optimising resource use, and observes that in each case most of the existing behaviour must stay the same. It contrasts two ways of working: making changes carefully and hoping, and making changes under a net of tests. It introduces the idea of a seam and the reasons for breaking dependencies. And it briefly surveys the tools a programmer needs, such as automated refactoring tools and unit-testing frameworks. This part is the theory of the book, though it is very practical theory.
The second part is organised by symptom rather than by technique. Each chapter is framed as a problem that a working programmer might actually say aloud, about time, about a class that will not go into a test harness, about not understanding the code, about a method so large that nobody can reason about it. Within each chapter Feathers explains why the problem arises and walks through approaches, often with code examples. A programmer can open the book at the chapter that matches today's trouble. This is an unusual organisation for a programming book and one of its main strengths.
The third part is a catalogue of named dependency-breaking techniques, each described as a short sequence of steps. It resembles the catalogue in Fowler's Refactoring, but its purpose is different. Fowler's refactorings assume that tests already exist. Feathers's techniques are designed to be applied safely when they do not, as the first steps towards getting tests in place.
Running through all three parts is a single procedure, which Feathers states early and returns to constantly. First, find the places in the code that need to change. Second, find where tests can be placed to cover those changes. Third, break the dependencies that stop those tests from being written. Fourth, write the tests. Fifth, make the change and improve the code around it. Most of the book is an elaboration of the third and fourth steps, because they are where the difficulty lies.
The argument moves from attitude to mechanics. It begins by persuading the reader that tests are the precondition for safe change. It then gives a way of thinking about code, in terms of seams and dependencies, that reveals where tests can go. And it ends with a toolkit for creating those openings. The examples move freely among Java, C++, C and C#, which is a deliberate choice: the problems of legacy code are not specific to any language, and neither are the solutions.
Legacy code is code without tests
The definition at the centre of the book is worth examining carefully, because it does more work than it first appears to. Most people use the word legacy loosely, to mean old, or inherited, or embarrassing. Feathers replaces this with a test. Code without tests is legacy code. The definition is not about quality in general. It is about one specific property, the presence or absence of a fast, automated way to check that the code still does what it did.
Why choose this property? Because it is what determines whether a team can change the code with confidence. Consider two systems. One is elegantly designed but has no tests. Another is clumsy but has a thorough suite of fast tests. Asked to add a feature to each, most experienced programmers would rather work on the second. In the first, every change requires careful reading, manual testing and a nervous release. In the second, a change can be made, the tests run in a minute, and the result is known. Over time the second system can be improved. The first tends to decay, because people avoid touching it.
The definition also changes how a team talks about its work. Instead of saying the system is a mess, which leads nowhere, a team can ask which parts are under test, which parts change most often, and which of those are not yet covered. That turns a vague complaint into a plan. It also gives a measurable direction: each change should leave a little more of the code under test than before.
It is often confused with a demand for complete test coverage. Feathers does not ask for that. He knows it is impractical for a large untested system and probably impossible. What he asks is that the code a programmer is about to change be brought under test first, and that each change extend the tested region a little. Over months the most active parts of the system, which are the parts that matter, become well covered. The dusty corners that nobody touches can stay untested until someone needs them.
The definition also implies a particular meaning of tests. Feathers is mainly concerned with unit tests: small, fast tests that exercise a piece of code in isolation, without touching databases, networks or file systems. He gives a rough rule that a unit test which takes a noticeable fraction of a second is too slow. The reason is that a programmer needs to run the tests constantly while changing code, and a slow suite will not be run. Larger tests, which exercise the whole system, have their place, but they do not give the quick, precise feedback that safe change depends on.
Where the definition leads is to a change in priorities. When faced with legacy code, the first question is not how to redesign it, nor how to add the feature quickly, but how to get the relevant part under test. That question, asked consistently, turns into everything else the book teaches.
Edit and pray, or cover and modify
Feathers contrasts two ways of changing code. In the first, which he names with gentle irony, a programmer studies the code carefully, plans the change, makes it, and then checks by hand that nothing seems broken, perhaps running the application and clicking through a few screens. Then the change is released and everyone hopes. This is how most changes to legacy code are made. Feathers calls it edit and pray.
Edit and pray is not careless. The programmer may be very careful indeed, but care is a weak defence against the complexity of a large system. The programmer cannot hold the whole system in mind. A change in one place may affect behaviour far away, through a shared variable, a database field or an assumption nobody wrote down. Manual checking covers a small fraction of the possibilities. Problems surface later, often in production, and are expensive to trace back to their cause.
The alternative is cover and modify. Before changing the code, the programmer puts tests around it, a covering net that records the current behaviour. Then the change is made, and the tests are run. If they pass, the existing behaviour has been preserved, at least as far as the tests reach. If they fail, the programmer knows at once, and knows roughly where. The tests act like a safety net under a trapeze: they do not stop mistakes, but they stop mistakes from being disasters.
An analogy from another field may help. A surgeon operating on a patient relies on monitors that report heart rate, blood pressure and oxygen continuously. The monitors do not do the surgery, but they let the surgeon know immediately if something goes wrong, so it can be corrected before it becomes serious. A surgeon working without monitors would have to be far slower and more conservative, and would still make more errors. Tests are the monitors of software change.
The important subtlety is that tests for this purpose are not mainly about finding bugs. They are about detecting change. A test suite for legacy code is valuable not because it proves the code correct, which it usually cannot, but because it tells the programmer when behaviour has changed. This is why Feathers is content to write tests that capture whatever the code does now, even if that behaviour is odd. The point is to notice when it stops doing it.
The feedback loop
Behind the definition of legacy code lies a broader idea about feedback. Feathers argues that the speed and precision of feedback determine how safely and how quickly a programmer can work. A programmer who learns within seconds that a change has broken something can correct it while the change is still fresh in mind. A programmer who learns weeks later, from a bug report, must first rediscover what was changed and why, and may by then have built other work on top of the mistake.
He distinguishes between large tests, which run the whole system or a big part of it, and unit tests, which run small pieces in isolation. Large tests are valuable, but they are slow, and when they fail they rarely say where the problem lies. A failing end-to-end test might mean a bug in any of a hundred places. A failing unit test usually points directly at the piece of code that changed. The difference is like the difference between a smoke alarm for a whole building and one in each room. Both are useful, but only the second tells you where the fire is.
Feathers adds a practical observation about why legacy systems resist this kind of feedback. In a well-tested system, building and running the tests for one part takes seconds. In a legacy system, the code is often so interconnected that compiling one class drags in hundreds of others, and running it requires the whole system to be configured. Much of the work of breaking dependencies is therefore also work on build times and test times. A dependency that forces a slow build is a cost paid every time anyone changes anything.
An analogy from learning a musical instrument fits. A student who records every practice session and listens immediately learns quickly, because each mistake is heard while the memory of making it is fresh. A student who only hears feedback at a monthly lesson repeats the same mistakes for weeks. The skill is the same in both cases. The rate of improvement depends on the loop.
This idea connects Feathers's book to the testing culture of Extreme Programming, which made fast feedback a central value. But his contribution is to show what it takes to create such a loop in code that was never designed for it. The loop does not appear by wishing for it. It must be built, one broken dependency at a time.
Tools and their limits
Feathers gives brief attention to tools, and his treatment is balanced. Two kinds matter most. Automated refactoring tools, built into development environments, can perform certain changes, such as renaming a method or extracting a block of code into a new method, with a guarantee that behaviour is preserved. When such a tool is available and trustworthy, it can make changes safely even before tests exist. Unit-testing frameworks, descended from the small frameworks written for Smalltalk and Java in the 1990s, provide the structure for writing and running tests quickly.
He also warns against trusting tools blindly. A refactoring tool is only as good as its analysis of the code, and some tools of the time made mistakes in edge cases, especially in languages with complex rules. A programmer should know what a given tool actually guarantees. Where the guarantee is weak, the programmer should treat the tool's output like any other untested change. The deeper point is that tools assist judgement but do not replace it. The skill of reading code for seams and effects remains necessary even when the tools are excellent.
He mentions as well tools for higher-level testing, in which business people write tables of examples that are run against the system. These can be useful for legacy systems, since they capture expected behaviour in terms the business understands. But they are slower and coarser than unit tests, and Feathers treats them as a complement to the techniques of the book rather than a substitute.
Seams
The most original idea in the book is the seam. Feathers defines a seam as a place where you can alter the behaviour of a program without editing the code in that place. Every seam has an enabling point, a place elsewhere where you decide which behaviour to use. The image is borrowed from tailoring: a seam is where two pieces of cloth are joined, and where a garment can be taken apart and altered without cutting the fabric itself.
Why does this matter? Because to test a piece of code in isolation, you usually need to replace some of what it depends on. A method that sends an email should not send real emails during a test. A class that reads from a hardware sensor should read from a fake sensor in the test. If the code is written so that the dependency is hard-wired, there is no way to substitute it without editing the code under test, which is exactly what you want to avoid before tests exist. A seam is a place where substitution is possible without such editing.
Feathers describes several kinds of seam. The most familiar in object-oriented languages is the object seam. If a method calls another method on an object it receives from outside, a test can pass in a different object, perhaps a subclass that overrides the troublesome method. The enabling point is wherever the object is created or passed in. Many dependency-breaking techniques in the book work by turning a hard-wired call into an object seam.
In languages like C and C++ there are other kinds. A link seam exists where the program is linked against a library: during testing it can be linked against a different library that provides fake versions of the same functions. The enabling point is the build configuration. A preprocessing seam exists in languages with a macro preprocessor: a macro can be redefined during testing to replace a function call with something else. The enabling point is a preprocessor definition. These seams are less elegant than object seams, but in old procedural code they are often the only ones available, and knowing about them opens possibilities that would otherwise be invisible.
The value of the concept is that it changes how a programmer looks at code. Instead of seeing a tangle of dependencies, the programmer looks for seams. Where can behaviour be substituted? Where is there an enabling point? If none exists near the code to be tested, what is the smallest change that would create one? This way of looking is a skill, and once learned it is hard to unlearn. Programmers who have read the book often find themselves noticing seams in code they read, the way a carpenter notices joints in furniture.
Seams are sometimes confused with interfaces or with dependency injection frameworks. They are related but broader. An interface is one way of creating an object seam. A dependency injection framework is a tool for managing enabling points in a large system. But a seam can exist without either, at the level of the linker, the preprocessor, a function pointer, or a method that a subclass can override. Feathers's concept is the general idea of which these are particular cases.
The idea also has a design lesson. Code with many seams is code whose parts can be separated, recombined and tested. Code with few seams is rigid. Over time, the work of introducing seams for testing tends to improve the design, because it forces dependencies to become explicit and separable. Testability and good design are not the same thing, but they are close neighbours.
Sensing and separation
Feathers names two reasons for breaking dependencies in order to test. The first is sensing. Sometimes code produces an effect that a test cannot see. It writes to a database, sends a message, changes a value in a hardware register, or updates a global object. A test needs to observe that effect to check it. Breaking the dependency lets the test substitute a fake that records what happened, so the effect can be sensed.
The second is separation. Sometimes code cannot even run in a test harness, because something it depends on is unavailable or slow. It needs a live database, a license server, a particular operating system service, or a large object that is painful to construct. Breaking the dependency lets the code be separated from that obstacle, so that it can run in isolation.
The distinction helps a programmer decide what kind of substitute is needed. For sensing, a fake object that records calls and values is often enough; the test then inspects what the fake recorded. For separation, a fake that simply does nothing, or returns harmless values, may suffice. Feathers discusses fake objects in some detail and also mock objects, which were then a newer idea: fakes that are given expectations in advance and check themselves. He is pragmatic about which to use.
A simple example. A class calculates a monthly bill and then sends it to a printer through a printer driver object. To test the calculation, a test must separate the class from the real printer, which is not available in the test environment, and must sense what would have been printed. Replacing the driver with a fake that stores the printed text in a string achieves both at once. The test can then check that the string contains the right total.
This pair of ideas is modest, but it brings clarity. Many programmers facing untestable code feel stuck because they cannot name what is wrong. Asking whether the problem is sensing or separation turns that feeling into a specific question with known answers.
Characterisation tests
When a programmer writes tests for new code, the tests express what the code should do. With legacy code that is often impossible, because nobody knows exactly what it should do. The original requirements are lost, the authors have gone, and the code has accumulated years of changes, some of which encode business rules nobody remembers. What is known is only what the code does now.
Feathers's response is the characterisation test. A characterisation test records the actual current behaviour of the code. The method is almost mechanical. Write a test that calls the code with some input and asserts that the result is something you know is wrong, such as an empty string. Run the test. It fails, and the failure message tells you what the code actually returned. Change the assertion to that value. The test now passes and documents one piece of real behaviour. Repeat with other inputs, focusing on the areas the coming change will touch.
The point is not to judge the behaviour but to pin it down. If the code calculates a discount in a way that seems odd, the characterisation test records the odd result. Perhaps it is a bug. Perhaps it is a business rule that customers rely on. Either way, the programmer now knows that a change has altered it, and can make that decision consciously rather than by accident. If a bug is found, it can be fixed as a separate, deliberate change, with its own test.
There is an analogy with a museum conservator restoring an old painting. Before touching anything, the conservator photographs and documents the painting exactly as it is, including cracks, stains and earlier repairs that may or may not be original. Only then does restoration begin, and every change can be compared against the record. Characterisation tests are that record for code.
Feathers adds practical guidance on how many characterisation tests to write and where. The aim is not to characterise the whole system but to cover the behaviour around the planned change thoroughly enough that any unintended effect would be caught. He suggests thinking about what the change could plausibly affect and writing tests there, and he describes ways of reasoning about the reach of a change, discussed below.
Characterisation tests are often confused with regression tests or acceptance tests. The difference is intent. A regression test checks that a known requirement still holds. A characterisation test checks that current behaviour, whatever it is, has not changed. It makes no claim that the behaviour is right. This frankness is what makes the technique work on code that nobody fully understands.
Small changes when time is short
One of the most practical problems in the book is the familiar one of having no time. A change is needed today, the code around it is untestable, and there is no room to spend a week breaking dependencies. Feathers does not pretend this situation away. He offers techniques for adding new behaviour in a way that is tested, even when the surrounding code is not.
The first is the sprout method. Instead of writing new logic inline in a long, untested method, the programmer writes the new logic as a separate method, tests that method on its own, and then adds a single call to it from the old code. The old method is still untested, but the new logic is, and the change to the old method is a single line that is easy to inspect. Over time, as more logic sprouts in this way, the old method may shrink.
The sprout class is the same idea at a larger scale. If the class that needs the change cannot be instantiated in a test harness at all, the new logic goes into a new class, which can be tested, and the old class creates and uses it. This can feel like adding clutter, and Feathers acknowledges that. But the new class is tested, its responsibility is clear, and it often becomes the seed of a better design.
The wrap method and wrap class work the other way. When new behaviour must happen before or after existing behaviour, such as logging every payment, the programmer renames the old method, creates a new method with the old name that calls the renamed one and adds the new behaviour, and tests the new part. Wrap class does the same with a class that wraps the old one and adds behaviour around it, a version of the decorator pattern described in Design Patterns.
These techniques have costs. They can scatter logic across more methods and classes than an ideal design would have. They leave the old code untested. Feathers is honest about this. His argument is that they are better than the alternative, which is adding untested logic to untested code and making the problem worse. They stop the bleeding while leaving room for proper treatment later.
An analogy is the way a city with an old, overloaded road network might add a new bypass rather than rebuilding the centre. The old streets remain as they were, but new traffic is handled by new road built to modern standards. The bypass does not solve the centre's problems, but it prevents them from getting worse and buys time for a proper redesign.
Deciding where to test
A programmer facing a change in legacy code must decide what to test. Testing everything is impossible. Testing only the line being changed is not enough, because the change may affect behaviour elsewhere. Feathers offers a way of reasoning about this decision that is one of the quieter strengths of the book.
The reasoning starts with the change points, the places where code will actually be edited. From each change point the programmer traces effects forward. Which values does this code compute? Which variables does it change? Which methods return results that depend on it? Which other parts of the system call those methods? Following these paths produces a picture of everything the change could plausibly affect. Feathers recommends drawing this picture by hand, since doing so forces attention to each step.
Once the picture exists, the programmer looks for good places to put tests. Feathers calls these interception points: places in the code where the effects of a change can be detected. The closer an interception point is to the change, the easier it usually is to write a test there, and the more precisely it reports what went wrong. But sometimes a point further away is better, because it gathers many effects at once. That is the pinch point mentioned elsewhere: a single method or object through which many of the change's effects must flow. A handful of tests at a pinch point can protect a wide area.
There is also guidance on how effects travel in typical code. Effects pass through return values, through changes to an object's fields, through changes to objects passed as arguments, and through global or static data. Global data is the hardest, because its effects can appear anywhere. Encapsulation, by limiting where a value can be changed and read, limits how far effects can travel, and so makes reasoning about change easier. This gives a concrete argument for good design that does not depend on taste: well-encapsulated code is code whose effects can be traced.
An example. A pricing method in a shop system is to be changed to handle a new kind of coupon. Tracing effects shows that the method's result is used by the cart total, which is used by the checkout page, the confirmation email and the accounting export. Writing tests at each of those would be slow. But all of them read the total from one method on the cart. That method is a pinch point. A set of characterisation tests on the cart total, covering the existing coupon types and a few ordinary orders, protects all the downstream uses at once.
Reasoning of this kind is easily skipped, because it feels slower than just making the change. Feathers's point is that it is much faster than finding the problem in production. And with practice it becomes quick, almost habitual. An experienced programmer begins to see the paths of effect through code the way an electrician sees circuits through walls.
Breaking dependencies safely
The third part of the book is a catalogue of dependency-breaking techniques. Each one is a short, named sequence of steps for loosening a particular kind of coupling. Their common feature is that they are designed to be applied without tests, so they must be very safe. Feathers achieves this in two ways: the changes are small and mechanical, and they preserve the signatures of existing methods wherever possible, so that callers are not affected.
Two habits underpin the catalogue. The first is preserving signatures. When moving code around without tests, Feathers recommends copying method signatures exactly, rather than rethinking parameters, because every rethinking is a chance to introduce an error. The second is leaning on the compiler. In statically typed languages, a programmer can make a deliberate change, such as changing a type or removing a declaration, and let the compiler report every place that is affected. The compiler then works as a crude but reliable tool for finding the reach of a change. Both habits trade elegance for safety, which is the right trade before tests exist.
The techniques fall into a few families. Some extract an interface from a concrete class, so that a test can provide a different implementation. Some parameterise a constructor or method, so that a dependency created internally can instead be passed in from outside. Some subclass a class and override a troublesome method, so that a test can use the subclass with harmless behaviour. Some deal with global variables and singletons, which are among the hardest dependencies to break, by adding a way to replace the global instance during tests. Some, for procedural code, use link or preprocessor seams to substitute functions.
Consider the most common case. A class creates a connection to a remote service in its constructor. In a test the service is unavailable, so the class cannot even be constructed. One technique is to add a second constructor that accepts the connection as a parameter, and change the original constructor to create the connection and pass it to the new one. Existing callers still use the original constructor and see no change. Tests use the new one and pass in a fake. The change is a few lines, can be checked by eye, and opens the class to testing.
Another common case is a method that calls a static method on some utility class, which in turn does something heavy. One technique is to extract the call into a new, small instance method on the class under test, then in a test subclass override that small method to do nothing or return a fixed value. Again, existing behaviour is unchanged, and a seam now exists where there was none.
Several of these techniques make the code temporarily uglier. A constructor that exists only for tests, a method made less private than it should be, a global with a setter for testing: all are compromises. Feathers is frank that these are scars, and argues that they are acceptable as long as they let tests in. Once tests exist, the code can be refactored properly, and many of the scars can be healed. A design made slightly worse but tested is in a better position than a design left pure and untouchable.
The catalogue is sometimes misunderstood as a set of design recommendations. It is not. These techniques are not how one would design new code. They are emergency measures for getting into old code with as little risk as possible. The design comes after, under the protection of the tests they make possible.
Understanding code you did not write
Much of the difficulty of legacy code is simply not understanding it. The book gives this problem serious attention, which is unusual. Most programming books assume that the reader understands the code, or will once they read it. Feathers knows that reading a large, tangled method can leave even an experienced programmer confused.
He describes several techniques for building understanding. One is sketching: drawing informal diagrams of the parts of the code that matter for the change, by hand, without worrying about notation. Another is a form of annotated listing, in which the programmer prints the code and marks it up, separating responsibilities, bracketing blocks, and noting where variables are set and used. Another is what he calls scratch refactoring, in which the programmer refactors the code freely, without tests, purely to understand it, and then throws the changes away. The refactored version reveals the structure; discarding it avoids the risk.
He also describes ways of reasoning about the effects of a change. An effect sketch is a small diagram showing which variables and methods can be affected by a change to a given piece of code, following the paths through which values flow. From an effect sketch a programmer can identify a pinch point, a narrow place in the code through which many effects pass, where a small number of tests can detect a large range of problems. Choosing tests at pinch points makes the characterisation effort efficient.
Another technique is telling the story of the system: explaining, in a few sentences, what the system or a component does, as one would to a newcomer. The exercise reveals what is essential and what is incidental, and it often shows that the code's structure does not match the simple story, which suggests where refactoring could help.
These techniques are all humble. They involve paper, pencils, conversation and throwaway changes. They reflect the reality that understanding comes before change and that understanding is built actively, not passively. A programmer who reads code only by scrolling through it on screen misses much of what these techniques reveal.
Monster methods and classes that grow
Two problems recur so often in legacy code that Feathers gives them special treatment. The first is the very large method, sometimes hundreds or thousands of lines long, which he calls a monster method. Such methods cannot be understood in one reading, cannot easily be tested, and grow larger because every new requirement is added inside them. He distinguishes, informally, between methods that are long sequences of loosely related sections and methods that are deeply nested tangles of conditions. The first are easier to break up than the second.
His advice for monster methods includes using automated refactoring tools where they exist, since a tool can extract methods more reliably than a person; extracting small pieces first, especially those that compute values without side effects; introducing sensing variables, temporary variables added just so a test can observe intermediate results; and gathering dependencies before attempting large restructuring. The emphasis is always on small, safe steps that make the next step easier.
The second problem is the class that keeps growing. Large classes accumulate responsibilities, each added by someone in a hurry. Feathers discusses ways of seeing the responsibilities hidden inside such a class, such as grouping methods by the variables they use, looking for methods that could be private, and looking for decisions that could change independently. He connects this to the single responsibility principle, the idea that a class should have one reason to change. His approach is not to redesign the whole class at once but to extract responsibilities gradually, each extraction tested.
An analogy from household life fits well. A drawer that has collected everything for years cannot be sorted in one go. One takes out the batteries and puts them in a box. Then the keys. Then the takeaway menus. Each small step makes the drawer a little more usable and the next step a little easier. A plan to reorganise the whole house first will never start.
Morale and the long view
The book ends on an unusual note for a technical work. Feathers addresses the feeling, common on teams working with large legacy systems, that things are hopeless. The code is bad, the deadlines are tight, and every change seems to make things worse. He acknowledges the feeling and offers a practical response.
His argument is that the techniques in the book make small improvements possible, and small improvements accumulate. A team that puts tests around each piece of code it touches will, over months, find that the parts of the system it works in most become safer and clearer. Work that once took days takes hours. The improvement is uneven, concentrated where the change is, but that is exactly where it matters. He also suggests that working on legacy code can be satisfying in its own way, since there is real pleasure in taking something tangled and making it clear.
This connects with an idea in The Pragmatic Programmer, also on this shelf, about not tolerating broken windows: small signs of decay invite more decay, and small repairs invite more care. It also connects with Peopleware's insistence that the conditions of work shape the quality of work. A team that believes its code can improve behaves differently from one that has given up.
There is a quieter lesson too. The book treats legacy code without contempt. It assumes that the people who wrote it were doing their best under constraints, and that the people now maintaining it deserve respect and good tools. This tone makes the book easier to use on real teams, where blaming predecessors is common and helps nobody.
The tradition around it
Working Effectively with Legacy Code sits at the meeting point of two lines of work. One is refactoring, given its classic form in Martin Fowler's Refactoring, which describes how to improve code structure in small, behaviour-preserving steps protected by tests. The other is test-driven development and the broader testing culture of Extreme Programming, described in Kent Beck's Extreme Programming Explained. Both assumed that tests existed or that code was being written fresh. Feathers addressed the case neither covered: code without tests that must change now.
Its catalogue form follows Refactoring and, before it, Design Patterns. Like those books, it gives names to techniques that experienced practitioners already used informally, and naming them makes them teachable and discussable. Several of its techniques use patterns from Design Patterns, such as the decorator in wrap class and the use of subclassing for substitution.
Other books on this shelf frame the problem from different angles. Code Complete and Clean Code describe how to write code well in the first place; Feathers deals with code that was not. The Pragmatic Programmer offers attitudes about craftsmanship and continual improvement that the book puts into practice. Domain-Driven Design by Eric Evans, also on this shelf, describes the anticorruption layer, a way of building a new model alongside an old system and translating at the boundary. Feathers works on the inside of the old system; Evans works at its edge. Together they cover most of the options for living with legacy software.
Site Reliability Engineering, also here, comes at old systems from the operational side, where the risk of change is measured in outages. Its emphasis on gradual rollouts and quick rollback is the production counterpart of Feathers's small, tested steps. A Philosophy of Software Design discusses how complexity accumulates through many small compromises, which is the process that creates legacy code in the first place.
After the book, the testing tools it describes became far more common. Mocking libraries, dependency injection frameworks and automated refactoring in development environments are now standard in most languages, which makes many of the techniques easier than they were in 2004. Feathers's vocabulary, especially seams and characterisation tests, spread widely. The broader practice of approval or golden-master testing, in which the output of a system is captured and compared against later runs, is closely related to characterisation testing and is now a common tool for legacy work.
Questions and criticisms
The most obvious limitation is age. The book's examples come from Java, C++, C and C# as they were in the early 2000s. Some techniques are less needed today, because modern tools do the work. Automated refactoring in development environments can safely extract methods and interfaces that Feathers describes doing by hand. Mocking libraries can create fakes for most classes without any changes to the code under test. Languages with first-class functions offer seams that were awkward to create in older Java or C++. A reader working in a modern language will find some chapters more historical than practical.
The principles, however, have aged very little. Code without tests is still risky to change. Dependencies still need to be broken to get code under test. Characterisation tests still work. Seams are still the right way to think about where substitution is possible. The book's tools have dated; its way of thinking has not.
A second criticism is that the dependency-breaking techniques can make code worse if they are applied and then never followed up. A codebase full of constructors added only for tests, methods widened from private to protected, and global instances with test setters can be harder to understand than before. Feathers says clearly that these are temporary measures, but in a hurried team they often become permanent. The fault lies in how the book is used rather than in what it says, but it is a real risk.
A third concern is the emphasis on unit tests. Some practitioners argue that for many legacy systems, especially those with heavy database or user-interface logic, higher-level tests that exercise the system through its real interfaces give more protection for less effort. Feathers does not reject such tests, but his techniques are mainly aimed at getting fine-grained unit tests in place. Later thinking on testing has given more weight to a balance of test types, and to tests that are robust to internal restructuring.
A fourth limitation is that the book says little about very large-scale legacy problems: replacing a whole system, migrating data, or gradually strangling an old application by routing more and more traffic to a new one. Those strategies are discussed elsewhere, notably in writing by Martin Fowler on what he calls the strangler fig approach. Feathers's focus is on the programmer at the keyboard, changing a specific piece of code. That focus is the source of the book's usefulness and also of its limits.
A fifth question concerns machine-generated code. Code produced quickly by tools, including code generators and assistants, can become legacy code almost at once if it arrives without tests. Feathers's definition applies to it without modification. If anything, the book's advice matters more when code is produced faster than humans can carefully read it, since tests become the main way of knowing what such code does.
What has held up most is the core claim. Tests are the precondition for safe change, and the work of getting code under test is worth doing incrementally, starting where the change is. Few practitioners today would dispute this. The book helped make it common sense.
Why it is on this shelf
This shelf holds books on Vedanta, Jyotish, science, economics and technology, chosen because each teaches a way of working carefully with something large and difficult. Working Effectively with Legacy Code belongs here because it teaches how to act responsibly on a system one does not fully understand. That is a situation far beyond software.
Every inherited body of knowledge is, in a sense, legacy code. A student who takes up an old tradition, whether a school of philosophy, a system of astrological calculation or a field of economics, inherits ideas whose original reasons are partly lost and whose current behaviour is known only by observing it. The sensible response is the one Feathers recommends: first record carefully what the system actually does, then make small changes and check their effects, and only then attempt larger reforms. Reform without such a record tends to break things that mattered for reasons nobody remembered.
For anyone building or maintaining software, the book is simply one of the most useful practical guides ever written. Every system becomes legacy code sooner than its authors expect, especially when it was built quickly. The definition at the book's centre is also a sound test to apply to any codebase handed over: before asking how good the design is, ask what tests exist and how quickly they run.
And the book models a temperament worth having. It is patient, unjudgemental and steady. It accepts imperfect conditions and still finds a way forward. That temperament is useful wherever work is done on things that were built by others and must be kept running.
How to read it
Read the first part straight through. It is short, and it gives the vocabulary that the rest of the book uses: the reasons for change, the contrast between editing and praying and covering and modifying, seams, sensing and separation, and the steps of the overall procedure. Spend extra time on the chapter about seams. With a pencil, take a piece of code you know and mark every seam you can find, noting its enabling point.
Then read two or three chapters from the second part that match problems you currently have. The chapters on having little time, on getting a class into a test harness, and on not knowing what tests to write are good starting points for most readers. Try the technique on real code within a day of reading. The book is learned by doing, not by reading.
Do not read the third part, the catalogue, from beginning to end. Skim its list of technique names so that you know what is there, then return to it when a problem calls for a specific technique. Work through one or two techniques in full on a small example, such as parameterising a constructor and extracting an interface, so that the mechanics become familiar.
Over the following weeks, read the rest of the second part as problems arise, or one chapter a week. Pay particular attention to the chapters on understanding code, effect sketches and monster methods, which reward slow reading. Write a characterisation test for a piece of code you have never tested; the first time is instructive.
Skip on a first pass the sections specific to languages you do not use, though the C and C++ material on link and preprocessing seams is worth a glance even for Java or Python programmers, because it widens the idea of what a seam can be.
From this shelf, read Refactoring alongside or just after, since it supplies the moves you will make once tests are in place. Read Domain-Driven Design for the anticorruption layer and the broader question of how a new model can grow beside an old system. Read Clean Code and A Philosophy of Software Design to form a picture of what the code should become. Read The Pragmatic Programmer for the habits that keep new code from becoming legacy code too soon.
Questions to carry
- Which parts of your current codebase are legacy code by Feathers's definition?
- How long does your fastest useful test suite take to run, and would you run it after every small change?
- In the code you will change next, where are the seams, and where are their enabling points?
- Is the obstacle to testing this piece of code a problem of sensing, of separation, or both?
- What does this code actually do now, as distinct from what you believe it should do?
- Which odd behaviours in the system might customers depend on?
- Where could a sprouted method or class let you add tested logic today without touching the old code much?
- Which dependency-breaking changes have you made that were meant to be temporary but became permanent?
- Where is the pinch point through which the effects of your planned change must pass?
- Which class in your system has the most reasons to change, and what is one responsibility you could extract from it?
- How would you tell the story of this component in three sentences, and does the code match the story?
- When did you last refactor code purely to understand it, and then throw the changes away?
- What would make your team believe that the code can improve?
- Is code produced quickly by tools in your project arriving with tests, or becoming legacy on arrival?
Words to know
- Legacy code: In Feathers's sense, any code without tests, whatever its age or quality.
- Unit test: A small, fast, automated test that exercises a piece of code in isolation from databases, networks and files.
- Test harness: The framework and setup that lets code be run and checked by automated tests.
- Edit and pray: Changing code carefully and then hoping nothing broke, without automated tests to confirm it.
- Cover and modify: Putting tests around code before changing it, so any unintended change is detected.
- Dependency: Anything a piece of code relies on that makes it hard to run or observe in isolation.
- Seam: A place where behaviour can be altered without editing the code in that place.
- Enabling point: The place where one chooses which behaviour a seam will use.
- Object seam: A seam created by substituting a different object, often a subclass or interface implementation.
- Link seam: A seam created by linking a program against a different library during testing.
- Preprocessing seam: A seam created by redefining macros so that different code is compiled for testing.
- Sensing: Breaking a dependency so a test can observe effects the code would otherwise hide.
- Separation: Breaking a dependency so code can run in a test harness at all.
- Fake object: A stand-in for a real dependency that behaves simply and may record what was done to it.
- Mock object: A fake given expectations in advance, which checks that it was used as expected.
- Characterisation test: A test that records what code currently does, without judging whether it is right.
- Sprout method: New logic written and tested as a separate method, then called from old code.
- Sprout class: New logic placed in a new, testable class used by an untestable old one.
- Wrap method: Adding behaviour before or after an existing method by renaming it and calling it from a new method.
- Preserve signatures: Copying method signatures exactly when moving code without tests, to avoid errors.
- Lean on the compiler: Using compiler errors deliberately to find every place affected by a change.
- Effect sketch: An informal diagram of what a change can affect, following how values flow through code.
- Pinch point: A narrow place in the code through which many effects pass, ideal for placing tests.
- Scratch refactoring: Refactoring code freely to understand it, then discarding the changes.
- Monster method: A method so long or tangled that it cannot be understood or tested as it stands.
A note on this edition
This is a study edition written for this shelf in our own words. It explains and comments on Michael Feathers's Working Effectively with Legacy Code without reproducing its text, code examples or catalogue entries, and the examples given here are our own. The book itself is in copyright. It is a working manual, best kept within reach while the code is open, and it is worth getting from a library or a bookshop.