Saturday, December 7, 2013

Intro to Refactoring with LEGOs

Practicing Into to Refactoring with LEGOs.

Refactoring is when a developer changes the structure of the code without changing the behavior.  To do this with little or no risk a craftsman will have a set of well maintained tests that prove the code still behaves exactly as before.

A simple way to visualize refactoring is to think of 12 eggs.  Most people will imagine a carton of eggs.  But it is possible to think of 2 cartons of 6 eggs; or even 6 packages of two hardboiled eggs.  Refactoring get's its name from the factorization of numbers.  Twelve has multiple factors (6 x 2), (3 x 4), (2 x 6), (1 x 12).  No matter which factorization the resulting collection is twelve eggs.  In TDD we have test to make sure we don't break the eggs.

Note:  Many IDE's claim to do refactoring, and many times they work just as expected; however not all IDE refactorings are reliable.  I suggest you test your IDE's refactoring before you trust it.

To introduce beginner developers to the basics of refactoring - start with a well understood class with many blocks of code.  First refactoring to practice is Extract Method.

But first make a program of blocks in this order:  white, red, blue, blue (again), red, yellow, green, red, yellow at the bottom.

Extract Method:  using the extract method refactoring - pull out the red block of code; replacing it with a call (the 4x2 red plate) to the extracted block.

Repeat the Extract Method operation on each red section of the program.

Now, a step of refactoring (or TDD) is to remove duplication.  All three of those red blocks of code are theoretically the very same, so we really only need one.  Set two aside and place the one remaining at the bottom of the program stack.

Good job!

Now let's use Extract Method operation on the two blue blocks of code.

And remove the duplication.  Remembering the one blue block remaining is place on the bottom of the program stack.

Practice, practice, practice.... the art of a craftsman.

Let's practice again with the yellow block;  perform the Extract Method operation on yellow blocks of code.

Well done.

Now the program looks a bit wonky... unbalanced by the large green block - let's extract it also.

There, good practice... and continue with the white block....

There all the in-lined class code has been extracted to methods and method calls.  That is well factored.  But let's do a bit of house keeping.  Clean up and reorder the methods and calls into a similar order.

When separated the blocks of code and the calling plates look like this:

Before and after refactoring images.

Required LEGOs

(1) Green 4x2 Plate;  (1) Green 4x2 Block
(1) White 4x2 Plate;  (1) White 4x2 Block
(2) Yellow 4x2 Plate;  (2) Yellow 4x2 Block
(2) Blue 4x2 Plate;  (2) Blue 4x2 Block
(3) Red 4x2 Plate;  (3) Red 4x2 Block


Adapted from Bryan Beecham's (@BillyGarnet TDD with LEGOs presentations and PDF.

Post a Comment