Practical software engineering foundations · Lesson 53 of 60 · Code lesson, JavaScript or Python · Optional
Refactoring
Refactoring means improving how code is organized without changing what it does.
Common moves are extracting repeated code into a function, giving things clearer names and removing duplication.
Make small steps and run your checks after each one.
Worked example
In JavaScript, a small function that returns the formatted price removes the repeated formula.
const TAX = 1.1;
function withTax(price) {
return (price * TAX).toFixed(2);
}
console.log("Tea: $" + withTax(3));Output: Tea: $3.30
In Python, a small function that returns the formatted price removes the repeated formula.
TAX = 1.1
def with_tax(price):
return f"{price * TAX:.2f}"
print("Tea: $" + with_tax(3))Output: Tea: $3.30
Your turn
The program prints two price lines with the same tax formula copied twice. Add a third line, Pie at 5, but instead of copying the formula again, move it into a function called withTax and use it for all three lines.
Expected output:
Tea: $3.30 Cake: $4.40 Pie: $5.50
Loading your practice…
Preparing your workspace…