iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📚

Personal Summary of Refactoring: Improving the Design of Existing Code (2nd Edition)

に公開
2023/01/14

https://amzn.to/3rpHRxR

About this article

This is a personal summary providing a rough overview and my impressions of each chapter of the book mentioned in the title.

Of course, it doesn't cover all the nuances of the original book, so I would be delighted if you would read it yourself if this sparks your interest. (I am still learning myself, and since I haven't read the original English version, I'm not in a position to be pretentious.)

Who is this for?

  • People who want to read it but are hesitant to buy because it's expensive
  • People who don't have much time to read
  • People who intend to read it and want to get an overview first
  • People who have read it and want to hear others' thoughts
  • People who have read it but don't really remember the content anymore

What for?

I wanted to write down a summary and my impressions for my own future reference. I also thought it might be helpful for someone else.

Book Structure

This book is a guidebook that clearly illustrates refactoring techniques, sample code, and cases where refactoring should be performed.

While JavaScript is used for the sample code, it avoids JavaScript-specific styles, so the code shouldn't be an issue if you can use other languages to some extent even if you don't know JavaScript. However, object-oriented concepts appear frequently, so you'll need to understand the general vibe of that.

The recommended way to read is described in the "Preface," and it's very helpful, so I'll excerpt it here.

  • If you want to know what refactoring is
    Read Chapter 1 (Refactoring: A First Example) to get a quick overview of the refactoring process.

  • If you want to know why to refactor
    Read Chapter 1 (Refactoring: A First Example) and Chapter 2 (Principles in Refactoring) to understand why it should be done.

  • If you want to know where to refactor
    Read Chapter 3 (Bad Smells in Code) to recognize the signs that indicate a need for refactoring.

  • If you want to actually perform refactoring
    Read Chapters 1 (Refactoring: A First Example) through 4 (Building Tests) thoroughly, then skim through Chapters 5 through 12 (the catalog section). For details, you can read them again when the need for actual refactoring arises.

So, you don't need to read everything strictly from the start. Awesome!
As it's a guidebook, it might be reassuring to keep it handy when you're actually refactoring. (Though we tend to forget it when we're in the thick of things, I know.)

Rough Overview and Impressions of Each Chapter

Chap.1 Refactoring: A First Example

A refactoring example is demonstrated using a relatively simple case.

The stages are:

  1. Decompose a large function.
  2. Separate into view and logic (in this example, the calculation part and the formatting part).
  3. Isolate logic using polymorphism.

Several important points that extend beyond just this chapter are discussed. (Including my own impressions)

What is Good Code?

The granularity and naming of functions are often a matter of preference, and it's frequently difficult to definitively state what is good or bad.
However, good code transcends preference; it is code that is easy to change.

"Easy to change" means the scope of a change is easy to foresee, it's clear where corrections are needed, there are few side effects from changes, and so on—code that doesn't hinder a programmer's productivity.

I tend to think that short and concise code is better, but in refactoring, the amount of code often increases, so I want to be careful about this point.

Don't Worry About Performance

People who care about performance might get worried during refactoring because variables are copied, or functions and loops increase.
However, only a small portion of a software's code actually affects speed performance, and most changes have almost no impact.

Even so, some refactorings do affect performance.
But even then, we continue regardless. This is because well-organized code makes it easier to understand what is happening and simplifies performance optimization.

Since I was reading while wondering about the performance impact, it felt like the author read my mind.
Indeed, if you blindly try to optimize performance from the start, you often end up focusing on local areas with little overall effect...

Testing is Essential

A mandatory condition for refactoring is that it must not change external behavior.
To ensure this, it's crucial to run tests frequently so that if a test fails, you know exactly what broke and can immediately revert to the previous working state. (Version control during refactoring stages while the code is still functional is also an important factor.)

In this book, the author very carefully introduces steps to avoid accidentally changing the original behavior during refactoring.

For each of those steps, the book repeatedly says "compile, test, commit." (Technically, JavaScript isn't compiled, but the principle holds.)

Doing those tests manually every time is practically impossible.
Furthermore, real-world code that requires refactoring is likely to involve much more complex and extensive steps, making automated testing absolutely essential.

Chap.2 Principles in Refactoring

This chapter is so well-organized that I honestly feel like if you're an engineer—or someone involved with engineering—who wants to know about refactoring, you could stop reading here. After highlighting the key points, I'll share my impressions.

Definition of Refactoring

Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.

That is to say, for example, if you try to do a large-scale refactoring and the code remains broken for several days, that cannot be called refactoring. In addition to the definition above, I believe it's important to proceed in small steps and repeat "compile, test, commit" at each step.

Why Refactor?

  • Improving software design

By refactoring regularly, you can keep the code in good shape.

No matter how good the initial design was, there is no software that doesn't undergo changes or additions. Unless corrected by an engineer who understands the code exceptionally well, the code will deteriorate.

Refactoring is necessary to stop this deterioration.

Personally, I feel that capable engineers refactor as naturally as they breathe, or rather, the flow between making changes and refactoring feels very natural (provided the original code isn't too terrible).

  • Making software easier to understand

By spending just a little time refactoring, you can better convey the purpose of the code and more clearly express what you want to achieve.

Even with code I wrote a short while ago, if I'm not careful, I often find myself thinking, "What is this?" So, keeping it in an easy-to-understand state is for your own sake as much as it is for others.

  • Helping to find bugs

When code is easy to understand, it's easy to find bugs.

In my experience, parts that feel "off" are almost always buggy...

  • Speeding up programming

To continue adding features quickly, refactoring has become essential.

This is a natural result of everything mentioned so far, but I find myself sighing because some workplaces don't easily accept this fact, given that refactoring itself takes man-hours.

Because things gradually become a black box, it's easy to just "sweep things under the rug" and leave them be. (Reflection.)

When Should You Refactor?

For Preparation

Performed to make adding a new feature easier, often done at the timing of feature additions.

For Understanding

Performed to make the code easier to grasp.

Personally, I found this sentence to be particularly excellent:

You are moving the understanding from your head into the code.

Litter-picking

As a variation of refactoring for understanding, this is performed when the way something is written is not quite right.

Even if the improvement is small, if everyone improves things a little bit, the code should get better... hopefully. It's the "leave the campsite cleaner than you found it" spirit.

Planned and Opportunistic Refactoring

It’s a common mistake to think of refactoring as an activity to clean up past mistakes or ugly code.

Even great code needs refactoring. Software never reaches a state of "completion," and when implementing new features, you need to change the code into a form that is easier to extend.

Therefore, most refactoring is done opportunistically and is an inconspicuous activity.

Long-term Refactoring

There are times when something takes a week or more, such as componentization or dealing with code with heavy dependencies.

However, because dedicating a team solely to refactoring is not recommended, it is advised to improve things bit by bit.
(This leverages the advantage that refactoring doesn't break the code.)

When replacing a library, it seems effective to introduce an abstraction layer for the library's interface.

During Code Review

Refactoring is also helpful when reviewing code written by others. This is because by refactoring, you can clearly grasp how the code changes when your own ideas are reflected in it.

According to the author, the most successful approach is to review and refactor the code alongside its author. In other words, pair programming.

To Persuade a Manager

There are workplaces where managers mistakenly believe that refactoring is just fixing past errors or work that produces no value.
For teams that perform reconstructions that could potentially break the codebase while calling it "refactoring," the situation becomes even worse.

Some managers or clients may not be able to technically understand the importance of refactoring. However, software developers should "just refactor."

This isn't a rebellion; as professionals, software developers are expected to build effective software as quickly as possible. The developer is responsible for the means used to implement a feature, and refactoring is simply one of those means.

I want to be able to refactor as naturally as I breathe. Inhale, exhale.

When Should I Not Refactor?

Sometimes refactoring has no value.

If there is no need for modification, there is no need for refactoring. For example, if it can be treated as a simple API, you might just leave it alone. The benefits of refactoring only emerge when you are in a situation where you need to understand the code.

Also, there are times when rewriting from scratch is easier than refactoring. However, making this decision is extremely difficult.

Problems with Refactoring

Various problems and countermeasures when performing refactoring.

  • Implementation slows down, such as in trivial cases for new features ➡️ If the feature you are trying to add is extremely trivial, you might postpone it. It's a trade-off.
  • Code ownership boundaries hinder refactoring ➡️ An organization where strong code ownership is not strictly set is ideal, but an approach like accepting open-source style PRs is a good compromise for large-scale systems.
  • Branching in version control worsens merge problems ➡️ The longer the branch, the greater the merge problems. The frequency of merging into the main branch should be high.
  • The hurdle for self-testing code is high ➡️ Self-testing code not only enables refactoring but also makes adding new features much easier, so it's a worthwhile effort. Development environments that support automated refactoring are also an option (though self-testing code is still better).
  • Legacy code ➡️ Please see Working Effectively with Legacy Code.
  • How to handle databases ➡️ It's best to break it down into multiple releases leading up to the final state. Prepare old and new fields for simultaneous operation and have mechanisms to revert changes immediately.

Refactoring and Architecture

In waterfall development environments, architecture was usually fixed once decided at the start.

The biggest impact refactoring has on architecture is that it provides a way to build a codebase with an excellent design that can flexibly respond to changing requirements.

It is almost never possible to fully understand the initial requirements of software in advance, and it is common to realize after building it that they cannot be achieved.

There are ways to develop with a certain amount of flexibility for that, but it's impossible to grasp or predict every pattern.
Instead, you can adopt a method where the architecture itself evolves flexibly by refactoring it to suit new requirements as user needs change.

Refactoring and the Development Process

Self-testing code is one of the foundations supporting refactoring. Having self-testing code gives you the confidence that if there's a mistake in the program, the tests will fail.

Also, when refactoring within a team, the use of Continuous Integration is recommended.
To incorporate refactoring into the development process, it's important that each member can refactor at any time without interfering with the work of other members.

Refactoring and Performance

An interesting fact about performance is that, when you analyze a program, most of the time is spent in a tiny fraction of the code. Therefore, even if you optimize uniformly across the entire code, 90% of that effort will be wasted.

So, it's necessary to first get the program into an organized state to identify that tiny fraction that is slowing things down. While refactoring might make things slower in the short term, it pays off in the end by making tuning easier.

Chap.3 Bad Smells in Code

In this chapter, the signs that might indicate a need for refactoring are listed.
*The names of the signs are quoted from the text, and I have added supplementary explanations for those that are difficult to understand.

Creating a table.

Name Symptom Countermeasures
Mysterious Name Variable, function, or field names are not appropriate Change to an appropriate name
Duplicated Code Code with the same structure exists in two or more places Extract Function, Slide Statements, Pull Up Method, etc.
Long Function Processing within a function is too long Various methods, but 99% is Extract Function
Long Parameter List Too many parameters required for calculation Replace Parameter with Query or pass objects instead
Global Data Global variables, class variables without access control, or Singletons exist Encapsulate Variable
Mutable Data Unexpected data changes occur Restrict or monitor value changes with Encapsulate Variable, Split Variable, etc.
Divergent Change One module is changed in different ways (having to fix multiple parts for a single addition) Move Function or Split Phase
Shotgun Surgery Every time you make a change, you have to make a lot of little edits to many different modules Move Function or Move Field to consolidate modules, or combine functions that handle similar data structures into a class
Feature Envy A function in one module interacts more with another module than with its own Move or split the function
Data Clumps Several data items hang out together in class fields or method signatures across various places Extract into a class to evolve them into an object, allowing data to be passed together
Primitive Obsession Avoiding the introduction of types for coordinates, ranges, currency, etc., and using primitive types instead Introduce objects
Repeated Switches The same conditional branch exists in various parts of the code Replace conditional logic with polymorphism
Loops Loops like for or while exist (now less important as pipeline operations can check elements and processing content more quickly) Replace Loop with Pipeline (filter, map, etc.)
Lazy Element There's a function with the same name as the processing inside, or a class with only one method Inline Function or Inline Class; if there is inheritance, Collapse Hierarchy
Speculative Generality There are features expected to be needed someday (but unused) or elaborate mechanisms that are not required Collapse into a hierarchy if it's an abstract class not doing much, or remove via Inline Function if it's a pointless delegation. Unused parameters and dead code should also be removed
Temporary Field An instance variable whose value is set only in specific circumstances exists Extract Class to move that variable, or create a new class via Move Function, or provide a substitute class for special cases
Message Chains A long sequence of method calls like getXXX is happening, or a series of temporary variables is receiving the results of getXXX Hide Delegation, or Extract/Move Function to consolidate the chain
Middle Man There is excessive delegation of authority brought about by encapsulation (e.g., a class where most methods just delegate to another object) Have the object that actually does the work handle the processing directly, or do it on the caller side via Inline Function
Insider Trading Modules are tightly coupled (many interdependent parts) Move Function or Move Field, add another module as a manager for shared data to loosen coupling. If caused by inheritance, replace the subclass or superclass with delegation
Large Class One class is doing too much work Extract Class, or replace type codes with Extract Superclass or Subclasses
Alternative Classes with Different Interfaces Interfaces don't match between classes Change Function Declaration or Move Function, or Extract Superclass to align interfaces
Data Class A class that has nothing but getters and setters Remove setters for things that shouldn't be changed, and consider if behavior can be moved to the data class via Move Function
Refused Bequest A subclass uses only a portion of the parent's attributes Create a sibling class and use Push Down Method/Push Down Field to move unused code to the sibling
Comments Comments are written to compensate for hard-to-understand code Refactor the original code itself to make it easier to understand

Chap.4 Building Tests

Automated testing significantly increases productivity, not just during refactoring.

This book only provides rough sample code and doesn't exhaustively cover the details of testing, but the execution of tests is mentioned repeatedly, and TDD (Test-Driven Development) is recommended.

Note that the sample code is in JavaScript using Mocha.

Personally, if I were to learn testing, I would list these books (which I read during my first year as an engineer):

https://amzn.to/3i248P7

https://amzn.to/371cYqg

https://amzn.to/3iSdI6K
*JUnit is a testing framework for Java.

Chap.5 Introducing the Catalog

Since specific refactoring catalogs are introduced from Chapter 6 onwards, this chapter only describes how they are presented.

Chap.6 A First Set of Refactorings

  • Extract Function
  • Inline Function
  • Change Function Declaration
  • Encapsulate Variable
  • Rename Variable
  • Introduce Parameter Object
  • Combine Functions into Class
  • Combine Functions into Transform
  • Split Phase

Described as the first set of refactorings to learn, they are introduced with common names, so most are understandable even without reading the details.

Chap.7 Encapsulation

  • Encapsulate Record
  • Encapsulate Collection
  • Replace Primitive with Object
  • Replace Temp with Query
  • Extract Class
  • Inline Class
  • Hide Delegate
  • Remove Middle Man
  • Substitute Algorithm

Information hiding from other modules and classes is a crucial perspective, especially as systems grow larger. I felt a slight sense of misalignment with "Substitute Algorithm" being here, but from the perspective that a function also encapsulates its implementation, it certainly belongs.

Chap.8 Moving Features

  • Move Function
  • Move Field
  • Move Statements into Function
  • Move Statements to Callers
  • Replace Inline Code with Function Call
  • Slide Statements
  • Split Loop
  • Replace Loop with Pipeline
  • Remove Dead Code

Pipelines can sometimes be confusing if you're not used to them, but personally, I think they look cool when used well and I quite like replacing things with pipelines.
Since Java didn't support lambda expressions until recently (well, a few years ago now), I didn't use pipeline replacements often, but I feel they are widely accepted now.

It’s wonderful to be able to take a flamethrower to unnecessary statements.

This line made me laugh.

Chap.9 Organizing Data

  • Split Variable
  • Rename Field
  • Replace Derived Variable with Query
  • Change Reference to Value
  • Change Value to Reference

Personally, with dynamically typed languages, I have an image that these things often become vague and difficult to understand. Depending on the language specifications, the distinction between reference and value can be blurred or very strict; I remember being quite confused when switching back and forth between Rust and JavaScript myself.

Chap.10 Simplifying Conditional Logic

  • Decompose Conditional
  • Consolidate Conditional Expression
  • Replace Nested Conditional with Guard Clauses
  • Replace Conditional with Polymorphism
  • Introduce Special Case
  • Introduce Assertion

I believe this is where the most unreadable code often arises due to code nesting.

When it comes to how to write conditional expressions, I feel it largely depends on one's ability to express the original specifications in clear natural language. Being able to describe such clear conditional expressions is wonderful.

In my personal opinion, "Introduce Special Case" and "Replace Conditional with Polymorphism" are particularly effective.

Chap.11 Refactoring APIs

  • Separate Query from Modifier
  • Parameterize Function
  • Remove Flag Parameter
  • Preserve Whole Object
  • Replace Parameter with Query
  • Replace Query with Parameter
  • Remove Setting Method
  • Replace Constructor with Factory Function
  • Replace Function with Command
  • Replace Command with Function

I think separating queries and updates is a fundamental concept for anyone who has designed things like Web APIs. However, since APIs are often public and have many users, a single change in how they are called can affect source code in many different places. This makes me feel that we really should put careful thought into hardening the interfaces as early as possible...

Chap.12 Dealing with Inheritance

  • Pull Up Method
  • Pull Up Field
  • Pull Up Constructor Body
  • Push Down Method
  • Push Down Field
  • Replace Type Code with Subclasses
  • Remove Subclass
  • Extract Superclass
  • Collapse Hierarchy
  • Replace Subclass with Delegate
  • Replace Superclass with Delegate

In the case of inheritance, there are more inverse patterns compared to other catalogs (e.g., Pull Up ↔ Push Down). I also think this is where what's "optimal" tends to change frequently as features are added.

Deciding which class should hold a feature, or whether to use inheritance or delegation, requires domain knowledge and experience. Since it's a powerful mechanism that is often misused, it's something we need to handle with care.

Overall Impressions

The code described in the book itself isn't difficult at all and was easy to understand, but it made me think about things like:

  • Whether I maintain an awareness of refactoring in my daily work.
  • Whether I'm repeating stopgap measures for feature additions or performance improvements, leaving the code without a clear overall perspective.

Since the refactoring catalog is so extensive, someone not used to it might need to pause and reflect while reading the source code to decide where to apply them.

Furthermore, real-world code is much messier, and I felt that the procedures for how to take steps to reach a refactored state can only be mastered through practice. Thus, I felt it's the kind of book you want to keep close at hand.

Sometimes there are "reversing" refactorings (for example, whether to move something into an abstract class or not), and there is no perfect answer for which to choose; you just have to select what seems appropriate for the current state.

If you deal with feature additions simply by piling up more code, the software will gradually deteriorate. Especially in an era of change where development under the waterfall model is difficult, I felt that the importance of refactoring in this way will only continue to increase.

Well, I think I've said something cool enough, so I'll end it here.
To everyone who has stuck with me this far, thank you very much!

Discussion