Refactoring Ruby Edition
When you find you have to add a feature to a program,
and the program's code is not structured in a convenient way to add the feature,
first refactor the program to make it easy to add the feature, then add the feature.
Before you start refactoring, check that you have a solid suite of tests.
These tests must be self-checking.
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
まずコードをわかりやすくする。パフォーマンスのことは後で考える
Defining 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.
Refactor (verb): To restructure software by applying a series of refactorings without changing its observable behavior.
リファクタリングでは、外から見た振る舞いを変えない
2つの帽子
機能追加
リファクタリング
refactoring is not an activity you set aside time to do.
Refactoring is something you do all the time in little bursts.
You don’t decide to refactor, you refactor because you want to do something else, and refactoring helps you do that other thing.
リファクタリングはそのために時間を設定してやるものではなく、何かをやるときに一緒にやるべきもの
If I need to add a new function and the design does not suit the change, I find it’s quicker to refactor first and then add the function.
“How difficult is it going to be to refactor a simple solution into the flexible solution?” If, as happens most of the time, the answer is “pretty easy,” you just implement the simple solution.
柔軟なものよりも単純でシンプルなソリューションを選ぶ
The lesson is: Even if you know exactly what is going on in your system, measure performance; don’t speculate.
推測するな、計測せよ
Bad Smells in Code
Dulicated Code
Long Method
メソッド抽出
コメントを書きたくなったら、代わりにメソッドを書く
名前重要
the real key to making it easy to understand small methods is good naming. If you have a good name for a method you don’t need to look at the body.
メソッド名が長くてもいい
We do this even if the method call is longer than the code it replaces, provided the method name explains the purpose of the code. The key here is not method length but the semantic distance between what the method does and how it does it.
コメントに注目する
A block of code with a comment that tells you what it is doing can be replaced by a method whose name is based on the comment. Even a single line is worth extracting if it needs explanation.
条件分岐・ループ
Conditionals and loops also give signs for extractions.
Most times when you see a case statement you should consider polymorphism.
apply Replace Inheritance with Delegation.
継承より委譲
コメントが必要だと思ったら、まずはコメントが不要になるようにリファクタリングしてみる
最初は失敗するようにテストを書く
テストはリファクタリングを行うための前提条件
一時変数から問い合わせメソッドへ
一時変数はそのメソッド内でしか参照できない
メソッド化すれば他のメソッドからも参照できる
引数に代入しない(引数を書き換えない)