This is the code that I have to refactor for my homework:
if (state == TEXAS) {
rate = TX_RATE;
amt = base * TX_RATE;
calc = 2 * basis(amt) + extra(amt) * 1.05;
} else if ((state == OHIO) || (state == MAINE)) {
rate = (state == OHIO) ? OH_RATE : MN_RATE;
amt = base * rate;
calc = 2 * basis(amt) + extra(amt) * 1.05;
if (state == OHIO)
points = 2;
} else {
rate = 1;
amt = base;
calc = 2 * basis(amt) + extra(amt) * 1.05;
}
I have done something like this
if (state == TEXAS) {
rate = TX_RATE;
calculation(rate);
}
else if ((state == OHIO) || (state == MAINE))
{
rate = (state == OHIO) ? OH_RATE : MN_RATE;
calculation(rate);
if (state == OHIO)
points = 2;
}
else {
rate = 1;
calculation(rate);
}
function calculation(rate)
{
amt = base * rate;
calc = 2 * basis(amt) + extra(amt) * 1.05;
}
How could I have done better?
Edit i have done code edit
amt = base * rate;
Steve’s point about the
switchstatement is a good one, but I’d like to suggest a different approach: arrays.If you store the rate information in an array and index into it by state, you can make maintaining this sort of code easier in the long term.
Consider this:
See what this might let a
calculatefunction do differently. (Note that in “real life”, theint rates[4]array could be done many different ways — a hashmap, a simple array ofstruct rate { char state[12]; int rate; }objects with state names and rates stored together at runtime, or a simple statically-assigned arrayint rates[4] = {0, 2, 3, 10};. I chose this because it shows indexing the array by#defined content.enumalso works.)