Saltar al contenido ForoHackers

Refactoring: start here

Refactorización
#849 · Ophuscado · · Denunciar

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

Inicia sesión o únete para responder.