🍃 Leaf

Refactoring

Refactoring is a technique for improving code structure with a quite specific condition, we do it without altering the system’s features. The idea is to make from it a day-to-day activity in which we make a series of small behavior-preserving transformations. That way we ensure that each step is less likely to go wrong (and if it does, it would be easy to fix), as well as reducing the chances of getting the system seriously broken.

To preserve the behavior of the system is to make changes without breaking any of the tests already defined before doing refactoring, for example. A change might be a renaming, splitting large functions into smaller ones (same for classes), use objects instead of a long parameter list, moving modules across architectural boundaries, among others.

The practice of doing “refactoring” has been there since the mid 80s, but it was adopted by Extreme Programming and then popularized by Martin Fowler in 1999.

The Two Hats & Not Refactoring

The two hats is a metaphor by Kent Beck about two distinct activities: altering features; and doing refactoring. They might be similar, but they are performed one at a time.

E.g.: We could be trying to add a new feature but we realize that the code is not scalable, so we need to swap hats and proceed to do some refactoring. When we are done, we swap hats again and continue with the feature. Things like this could happen in about 15 minutes several times a day. This stresses that refactoring only aims to improve code quality.

There is also the four hats metaphor in which we make a distinction between interface and implementation related activities (for both altering features and doing refactoring).

Things that refactoring is not:

When to Refactor

We do it when code smells, often an indicator of a problem (not always the problem itself):

Refactoring Benefits

In general the benefit is to avoid any point described above, improvements are:


Reference: