{"canonical_url":"https://engineer.company/glossary/refactoring/","content_markdown":"# Refactoring\n\n## What it is\n\nRefactoring is changing the internal structure of code without changing what\nthe code does for anyone who uses it. Names, function boundaries and the layout\nof modules change; inputs, outputs and side effects stay exactly as they were.\nThe verb is to refactor, and one such change is also called a refactoring.\n\nMartin Fowler defines the term in his book Refactoring, and restated the\ndefinition on his website in 2004. As a noun, a refactoring is one change to\nthe inner structure of software that makes the code easier to understand and\nless costly to change, while what it does as seen from outside stays the same.\nAs a verb, to refactor is to carry out a sequence of such changes, with that\noutside behaviour unchanged throughout. Both halves matter. The purpose is a\ncheaper next change, and the constraint is that nobody outside the code can\ntell that anything happened.\n\nFowler draws the line sharply: \"Refactoring isn't another word for cleaning up\ncode,\" he writes on refactoring.com. It names one specific technique. He uses\nrestructuring as the wider word for reorganising code by any means, including\nones that do not preserve behaviour at every step. What makes refactoring a\ntechnique is its size. Each step is a small transformation that does little by\nitself and is unlikely to go wrong, and the whole system still works after\nevery one. A long sequence of them can still add up to a large change in\nstructure.\n\nThe steps have names. The catalogue on refactoring.com, which accompanies the\nsecond edition of the book, lists them with the older names they replace:\nExtract Function, also known as Extract Method, and its inverse Inline\nFunction; Inline Variable; Rename Variable; Move Function; Split Phase, and\ndozens more. A shared name lets a developer say what a change was in two words,\nand lets a reviewer check it against a known recipe.\n\n## Why it matters\n\nSoftware that succeeds keeps changing. New features and fixes are layered on\ntop of each other, and each one tends to make the next a little harder, until,\nas Fowler describes it, adding anything new takes painfully long. Refactoring\nis the counterweight: it reshapes the code so that each addition does not bring\ncomplexity it does not need. Its return is measured in the cost of the next\nchange, not in the look of the code.\n\nThat is why Fowler treats it as part of ordinary programming rather than a\ntask that appears in a project plan. He names three moments. Before adding a\nfeature, he checks whether the code is shaped to make the feature easy, and\nrefactors first if it is not, which he usually finds quicker than forcing the\nfeature in. After the feature works, he refactors the result into a shape that\nsomeone returning in a few weeks can follow without puzzling. And when he has\nto read unfamiliar code to understand it, he refactors so that the next reader\ndoes not struggle in the same place. The first of these has its own name,\npreparatory refactoring, and Fowler credits Kent Beck with the rule behind it:\nfor every change, first reshape the code until the change is easy, which can\nbe the hard part, and only then make it.\n\nRefactoring also keeps risk low in a way that feature work cannot. Fowler\npasses on another of Beck's metaphors, the two hats. While wearing the\nrefactoring hat, every change preserves behaviour and the tests stay green\nthroughout. While adding function, tests are added and existing ones break,\nwhich is more stressful and riskier. A developer who knows which hat is on\nknows what a failing test means: during a refactoring, it means the last step\nwas wrong.\n\nThe same idea is how most technical debt gets repaid. The Google paper on\nhidden debt in machine learning systems lists refactoring code first among the\nways to pay debt down. Tools help: many languages now have editors that\nautomate common refactorings. Fowler counts such tools as valuable but not\nessential, and where they are missing he relies on small steps and frequent\ntests.\n\n## What it looks like in practice\n\nTake a function, written for this article, that totals an order and prints a\nreceipt in one place:\n\n```javascript\nfunction printReceipt(order) {\n  let total = 0;\n  for (const line of order.lines) {\n    total += line.price * line.quantity;\n  }\n\n  // print the receipt lines\n  console.log(`Order ${order.id}`);\n  console.log(`Total: ${total}`);\n}\n```\n\nA new requirement arrives: the same total must appear on an invoice. Rather\nthan copy the loop, the developer first refactors. Step one is Extract\nFunction: the loop moves into its own function, named for what it computes, and\nthe tests run. Step two extracts the printing the same way, so that a function\nname replaces the comment, and the tests run again. Step three is Inline\nVariable: the `total` variable is now used only once, so the call takes its\nplace. After each step the program does exactly what it did before and could be\ncommitted on its own:\n\n```javascript\nfunction printReceipt(order) {\n  printLines(order.id, orderTotal(order));\n}\n\nfunction orderTotal(order) {\n  let total = 0;\n  for (const line of order.lines) {\n    total += line.price * line.quantity;\n  }\n  return total;\n}\n\nfunction printLines(id, total) {\n  console.log(`Order ${id}`);\n  console.log(`Total: ${total}`);\n}\n```\n\nOnly now does the feature go in, and it is one line in the invoice code that\ncalls `orderTotal`. Nothing in the three refactoring steps needed a new test,\nbecause nothing observable changed; the tests that already covered the receipt\nare what prove it.\n\nInfrastructure code is refactored as well, and there the stakes are higher,\nbecause the names refer to running resources. Terraform's documentation warns\nthat, by default, giving a resource a new address in the configuration tells\nTerraform to tear down the one that exists and build a fresh one. Renaming\n`aws_instance.a` to `aws_instance.web` for readability would therefore replace\na server. Since Terraform v1.1, a `moved` block records the old address\ninstead, and the next plan updates the address without destroying anything:\n\n```hcl\nresource \"aws_instance\" \"web\" {\n  # (configuration unchanged)\n}\n\nmoved {\n  from = aws_instance.a\n  to   = aws_instance.web\n}\n```\n\nOn earlier versions, the documentation points to the `terraform state mv`\ncommand for the same move. Either way the refactoring is only safe once the\nplan has been read and shows a move, not a destroy and a create.\n\nKeeping such changes separate from feature work is easier when the history\nsays which is which. The commit standard described in this site's portfolio\nentry on\n[holding four repositories to one history standard](/portfolio/held-4-repositories-to-one-history-standard/)\nstarts every commit message with a conventional prefix naming the kind of\nchange, enforced by a commit-message hook. The page, on work carried out in\nJuly 2026, counts 26 refactors in the largest repository's history beside 156\nfeature commits and 133 fixes. The same page is honest that the hook checks the\nformat and not the content. A commit labelled as a refactor still has to be\nshown by its tests and its review to have left behaviour alone.\n\n## Where it goes wrong\n\n**Behaviour changes ride along with the refactoring.** A developer tidies a\nfunction and fixes a bug in it in the same commit. When a test fails, nobody\ncan tell which of the two caused it, and a reviewer has to read every line as\na possible change in behaviour. Wear one hat at a time: refactor in one commit,\nchange behaviour in the next, and if a test fails while refactoring, undo the\nlast step instead of fixing forward.\n\n**A large restructuring is called refactoring.** A branch spends weeks with\nthe build broken while the code is \"being refactored\". That is restructuring,\nin Fowler's terms, and it carries the risk refactoring is designed to avoid.\nBreak the work into steps that each leave the system working and can be merged\non their own; where that is not possible, call it a rewrite and plan it as one.\n\n**There are no tests to show nothing changed.** Behaviour preserved is a claim,\nand without tests it is a guess. Before touching code that has no tests, write\ntests that pin down what it does today, even where that looks wrong, and fix\nthe oddities in separate changes afterwards. Fowler's rule of thumb from his\npreparatory refactoring example applies here: whenever the urge comes to run\nthe code and inspect its output by eye, write a test instead.\n\n**A rename in infrastructure code replaces the resource.** A tidy new name in\nTerraform reads like a refactoring in review, and the plan quietly proposes to\ndestroy a database and create an empty one. Record every rename and every move\ninto or out of a module with a `moved` block, and treat any destroy in the plan\nof a change meant as a refactoring as a failed step.\n\n**An old `moved` block is deleted.** Moved blocks accumulate, and removing\nthem looks like housekeeping. The Terraform documentation calls it a breaking\nchange: any configuration that still uses the old address would then get a\nplan that destroys the object rather than moving it. Keep the historical\nblocks, chain them when an object is renamed twice, and remove them only from a\nprivate module once everyone using it has applied the version that contains\nthem.\n\n**Refactoring waits for a dedicated phase.** A team that schedules a\n\"refactoring sprint\" for later keeps adding features to code that resists\nthem, and a sprint planned for later is easy to cut when a deadline moves.\nFowler's advice runs the other way: refactor as part of each change, first to\nmake the change easy and afterwards to leave the result clear, so that the\nwork never needs a slot of its own in the plan.\n\n## Further reading\n\n- [Definition Of Refactoring](https://martinfowler.com/bliki/DefinitionOfRefactoring.html)\n  — Martin Fowler's noun and verb definitions, as given in his book.\n- [Refactoring](https://refactoring.com/) — Fowler's site for the book, with\n  why refactoring is part of daily programming and the full catalogue.\n- [Extract Function](https://refactoring.com/catalog/extractFunction.html) —\n  the catalogue entry for one of the most common refactorings, with its inverse\n  and its first-edition name.\n- [An example of preparatory refactoring](https://martinfowler.com/articles/preparatory-refactoring-example.html)\n  — Fowler reshapes his own code in small steps before adding a feature, and\n  explains the two hats.\n- [Refactor modules](https://developer.hashicorp.com/terraform/language/modules/develop/refactoring)\n  — Terraform's documentation on `moved` blocks, renames, splitting modules\n  and why old blocks should stay.\n\n\u003chttps://engineer.company/glossary/refactoring/\u003e\n","date_modified":"2026-10-29T11:17:41Z","description":"What counts as refactoring and what does not, how small steps keep code working, how to rename infrastructure safely, and where refactoring goes wrong.","formats":{"gemtext":"https://engineer.company/glossary/refactoring/index.gmi","gopher":"https://engineer.company/glossary/refactoring/gophermap","html":"https://engineer.company/glossary/refactoring/","json":"https://engineer.company/glossary/refactoring/index.json","markdown":"https://engineer.company/glossary/refactoring/index.md","pdf":"https://engineer.company/glossary/refactoring/index.pdf"},"kind":"page","language":"en","title":"What is refactoring?","url":"https://engineer.company/glossary/refactoring/","version":1}