Refactoring is a crucial practice in software engineering, especially when working on long-term projects or maintaining existing codebases. It's all about improving the structure and readability of your code, while ensuring it still functions correctly.
Let's say we have a function that calculates the area of a rectangle:
function calculateRectangleArea(length, width) {
if (length <= 0 || width <= 0) {
return "Invalid input. Please provide positive numbers.";
}
return length * width;
}We can refactor this function by first writing a test:
function testCalculateRectangleArea() {
expect(calculateRectangleArea(2, 3)).toEqual(6);
expect(calculateRectangleArea(0, 5)).toEqual("Invalid input. Please provide positive numbers.");
}Next, we refactor the function:
function calculateRectangleArea(dimensions) {
const [length, width] = dimensions;
if (length <= 0 || width <= 0) {
return "Invalid input. Please provide positive numbers.";
}
return length * width;
}Now we can run our test to ensure the refactored function still works:
testCalculateRectangleArea();What is the main purpose of refactoring in software engineering?
When should you refactor your code?