Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Just add percentage
The second step of refactoring is now behind us. The console has the same results: 660 miles and 540 miles. Which means that we did not ruin the logic and the refactoring was successful.
Due to the fact that we refactored our code, writing another if
into the function is quite simple:
var calculateMiles = function (distance, isBusinessClass) {
var percent = 0.18;
if (isBusinessClass) {
percent += 0.04;
}
if (distance > 3500) {
// Let’s change percentage one more time
}
return distance * percent;
};
And what happens if we fail to enter a percentage variable and decrease the number of exits from the function?
calculateMiles
code will look very scary. It will be something like this:
var calculateMiles = function (distance, isBusinessClass) {
if (isBusinessClass && distance > 3500) {
return distance * 0.37;
}
if (isBusinessClass && distance <= 3500) {
return distance * 0.22;
}
if (!isBusinessClass && distance > 3500) {
return distance * 0.33;
}
return distance * 0.18;
};
Or no less scary. Like this:
var calculateMiles = function (distance, isBusinessClass) {
if (isBusinessClass) {
if (distance > 3500) {
return distance * 0.37;
} else {
return distance * 0.22;
}
} else {
if (distance > 3500) {
return distance * 0.33;
} else {
return distance * 0.18;
}
}
};
And this is only for two conditions that affect the mile calculation process. Imagine how cumbersome the code will become if there is one or two new conditions for calculating miles (which in real practice is quite common).
- script.js
Thanks! We’ll fix everything at once!
The code has changed, click “Run” or turn autorun on.
Comments