I would just add a tiny little bit to Kent Beck’s

If you can’t make it better, make it worse.
(Kent Beck)

and that is “in order to make it even better“.

I don’t know where I stumbled over defactoring for the first time. It might had been in one of Kent Beck’s videos about TDD, that I bought once or here or here.

But just a little bit ago in one of my TDDbin sessions it fell in my lap and happily used it. The following video shows how I got from this code

if (out[0] > out[1]) {
  out = [out[1], out[0]].concat(out.slice(2));
if (out[2] > out[3]) {
  out = out.slice(0, 2).concat([out[3], out[2]]).concat(out.slice(4));
if (out[3] > out[4]) {
  out = out.slice(0, 3).concat([out[4], out[3]]);

to that code

out = swapNeighbours(out, 0);
out = swapNeighbours(out, 2);
out = swapNeighbours(out, 3);
function swapNeighbours(out, offset) {
  if (out[offset] > out[offset + 1]) {
    out = out.slice(0, offset).concat([out[offset + 1], out[offset]]).concat(out.slice(offset + 2));
  return out;

To make a long story short, I think watching those 5 minutes of the video will explain best what it is.

I am curious about your experiences with defactoring, please leave a comment.