Skip to the content ForoHackers
Log inJoin

Refactoring: start here

Refactoring
#3355 · · Quote · Report

Refactoring is changing the structure of code without changing what it does, so that the next change is easier. It is done in small, safe steps, each checked by tests, and it is how a codebase stays healthy instead of rotting. If behaviour changes, it was not a refactoring.

Key concepts

  • Behaviour preserved: tests, types and small steps prove nothing broke.
  • Code smells: long functions, duplication, big classes and tangled conditions hint at where to look.
  • Small named moves: extract function, rename, inline, move, replace conditional with polymorphism.
  • Tests first: with no tests, write characterisation tests that pin down what the code does today.
  • Separate hats: refactor or add a feature in one commit, never both.

Vocabulary

  • Code smell: a surface sign that a design may have a problem.
  • Technical debt: the future cost of a shortcut taken now.
  • Characterisation test: a test that records current behaviour, right or wrong.
  • Strangler approach: replacing a system piece by piece while it keeps running.

What to study, in order

  1. Take a messy function of your own and apply extract function and rename until it reads like prose.
  2. Learn the catalogue of named refactorings and the smells that call for each.
  3. Add characterisation tests to untested code, then restructure it.
  4. Use your editor's automated refactorings and compare them to doing it by hand.
  5. Plan a larger change as a sequence of steps that each leave the program working.

Related tags

#testing #design-patterns #maintenance #code-review

You are not logged in, so this goes up anonymously: no account, no name and no address is stored with it, and it may carry no link and no image. Log in or join to post under your name. Our web server's logs keep the address and time of every request for up to 14 days; to keep yours out of them, use Tor. To reach the staff in confidence, use the drop. Sign as a returning source (a key kept only in this browser)

Sending takes a few seconds here: your browser first works out a proof of work against spam.

Reply