Using Extract Variable
Extract Variable is a common refactoring technique that is used to improve the readability and maintainability of code. The process involves taking a section of code that calculates a value, replacing it with a new variable, and assigning the result of the original expression to this new variable. There is a similar refactoring called Extract Constant that can be used to extract a value that doesn’t change at runtime.
This refactoring technique is particularly useful when you have a complex expression or a duplicated calculation; by extracting parts of the expression to variables with meaningful names, the code becomes more understandable and easier to manage.
In the ShoppingCart
example, the 0.9
discount rate deserves its own name; we can extract a variable and reference it at the point where the function is called. As the value of the variable isn’t going to change at runtime, we can call it Extract Constant in this case:
const DISCOUNT_RATE...