Section 6.1 Introduction to refactoring
Subsection 6.1.1 What is refactoring
One of the essential practices in maintaining code is refactoring:
Refactoring is a change in the structure of the code without change in behavior.Refactoring is typically performed via a series of small steps, each of them changing the code in a small way while preserving the same functionality.An essential property of the refactoring process is that it does not leave the code broken for more than a few seconds or a minute. When you go through a refactoring process, some time in the last minute or two your code was running perfectly fine. And you can get back to that state with a couple of Undo steps, if you need to.
There is a long list of refactoring steps, and I will direct you to Fowler’s excellent reference on the subject (TODO: Reference here) for that full list. In this section we will encounter some of the most common ones.
While you can do refactoring steps by hand, and some times you have to do just that, most modern IDEs offer a lot of these steps automatically. When a refactoring can be done automatically in a safe way, IDEs like IntelliJ will do it for you.
I like to group the various refactorings in two broad categories:
- There is a set of every day refactorings, that are so standard, commonplace, and likely to be used on a regular basis. These will be the focus of this chapter.
- There are a number of rare refactorings, which are used in more specialized situations, and we will discuss those spread across the rest of the book, when the specific topic calls for them.
Subsection 6.1.2 What and when to refactor
Let’s answer the question of "when" to refactor first. Ideally, you want to refactor as soon as your code is in a "green state", with the most recent test you wrote passing. We will discuss this idea more in the Test-Driven-Development sections. But the key idea is this:
Refactor as you go, don’t plan for a big refactoring effort once a month or something.
Now let’s focus on the what: How do we know what refactoring steps we should be taking? The answer to that question is what we call code smells:
A code smell is a certain property of the code’s structure or design that suggests there is something wrong. When you encounter a code smell, there are likely associated refactoring steps you can take to remedy the situation.
The list of code smells is too long, so we will focus on a few of them here. You can consult (TODO: reference clean code and Fowler) for a longer listing.