15 C
New York
Wednesday, May 14, 2025

The three refactorings every developer needs most



RecordNumber beats RecNo and CustomerRecordNumber beats RecordNumber. CustomerNumberCannotBeZero is a better name for a boolean than doing CustNo > 0. Naming is hard, but if you take the time, you can give everything a proper name. And if you realize you need a different name, having the Rename refactoring available should embolden you to freely and brazenly name things clearly and precisely. Clear and expressive names are always winners.

Extract Variable

All too often, we get into a hurry when we are coding. For instance, we’ll type something like this:


If CalculateInterestRate(GatherAllInputs()) > 0.6 {
  …
}

In other words, we pass a function result directly into another function as part of a boolean expression. This is… problematic. First, it’s hard to read. You have to stop and think about all the steps. Second, and more importantly, it is hard to debug. If you set a breakpoint on that line, it is hard to know where the code is going to go next. 

However, if you extract all that code out into something more readable and debuggable, you have a much better result:


const AllTheInputs = GatherAllInputs();
const CustomerInterestRate = CalculateInterestRate(AllTheInputs);
const CustomerInterestRateIsHighEnough = CustomerInterestRate > 0.6;
If CustomerInterestRateIsHighEnough {
  …
}

That’s clean, lovely code that is easy to read and easy to debug. It’s also easy to “write” with the Extract Variable refactoring tool. 

And to those of you who say that’s too much typing, I say, “Laziness is not a career-enhancing move.”

Extract Method, Rename Variable/Method/Class, and Extract Variable are not the only refactoring tools in the toolbox, but they are the most useful. They are the ones that provide the most benefit. If I had to choose only one to use, I’d pick Extract Method, because it is the strongest defense against the common problem (temptation?) of sprawling methods. 

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles