How is refactoring done?
Refactoring.com calls it a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behaviour [1]. The work proceeds as a series of small, behaviour-preserving transformations. Each one does little on its own, but a sequence of them can produce a significant restructuring [1].
The system is kept fully working after each step, which reduces the chance of seriously breaking it during the restructuring [1].
What does it look like in practice?
One of the best-known entries in the catalogue is Extract Function, also known as Extract Method [3]. In the example, the printOwing function contains two lines, flagged by a comment, that print the customer's name and the amount owed. After the refactoring those lines live in a separate printDetails function, and printOwing simply calls it [3]:
printBanner();
let outstanding = calculateOutstanding();
printDetails(outstanding);The output is identical. Only the shape of the code has changed.
How is it different from fixing a bug?
In Martin Fowler's definition, a refactoring is a change made without altering observable behaviour [2]. As a verb, to refactor is to restructure software by applying a series of refactorings, again without changing what it does [2]. Fixing a bug or adding a feature does change behaviour, which is why the two are treated as separate kinds of work.