ℹ️ This repository is part of my "refactoring" catalog based on Fowler's book with the same title. Please see kaiosilveira/refactoring for more details.
Formerly: Inline Temp
Before | After |
---|---|
let basePrice = anOrder.basePrice;
return basePrice > 1000; |
return anOrder.basePrice > 1000; |
Inverse of: Extract Variable
Sometimes a variable is as clear and short as the expression it is derived from, and sometimes it gets in the way of refactoring the code surrounding it. In these cases, it is often best to delete the variable and inline the originating expression.
For this refactoring, we are going to analyze a function that returns a boolean saying whether an order is eligible for a discount. It returns true
if the basePrice
of the order is greater than 1000
and false
otherwise. The starting code looks like this:
function isEligibleForDiscount(anOrder) {
const basePrice = anOrder.basePrice;
return basePrice > 1000;
}
Two tests were added to cover this refactoring: one for when the function returns true
and another for when it returns false
:
describe("isEligibleForDiscount", () => {
it("should return true if order.basePrice is greater than 1000", () => {
const anOrder = { basePrice: 1001 };
const isEligible = isEligibleForDiscount(anOrder);
expect(isEligible).toEqual(true);
});
it("should return false if order.basePrice is less than 1000", () => {
const anOrder = { basePrice: 999 };
const isEligible = isEligibleForDiscount(anOrder);
expect(isEligible).toEqual(false);
});
});
To perform this refactoring, we first replace the variable by its originating expression:
diff --git a/index.js b/index.js
@@ -1,6 +1,6 @@
function isEligibleForDiscount(anOrder) {
const basePrice = anOrder.basePrice;
- return basePrice > 1000;
+ return anOrder.basePrice > 1000;
}
module.exports = { isEligibleForDiscount };
And then simply remove the now unused variable:
diff --git a/index.js b/index.js
@@ -1,5 +1,4 @@
function isEligibleForDiscount(anOrder) {
- const basePrice = anOrder.basePrice;
return anOrder.basePrice > 1000;
}
And that's it!
See below a chronology (from top to bottom) of all the refactoring steps:
Commit SHA | Message |
---|---|
8009aae | replace variable by originating expression |
6eb1a50 | remove unused variable basePrice |
The full commit history can be seen in the Commit History tab.