'Refactoring if statements with radiobuttons.checked
There are two radio buttons which give different prices. Example: elektric2 is selected and 3 days rent. Electric bike = 200 euro + 30 euro per day (200 eu + (30*3)).
How can I refactor this because I have 60+ lines of code for all the options.
Here is a bit of the entire code:
if (radioButtonElectric2.Checked && radioButtonADay.Checked)
{
electric2 = electric2 + 1 * 30;
labelSubTotal.Text = "Subtotal:€" + electric2.ToString();
}
else if (radioButtonElectric2.Checked && radioButtonThreeDays.Checked)
{
electric2 = electric2 + 3 * 30;
labelSubTotal.Text = "Subtotal:€" + electric2.ToString();
}
else if (radioButtonElectric2.Checked && radioButtonSevenDays.Checked)
{
electric2 = electric2 + 7 * 30;
labelSubTotal.Text = "Subtotal:€" + electric2.ToString();
}
else if (radioButtonElectrical2.Checked && radioButtonFourteenDays.Checked)
{
electric2 = electric2 + 14 * 30;
labelSubTotal.Text = "Subtotal:€" + electric2.ToString();
}
Solution 1:[1]
Your equation basically boils down to three amounts.
- Base Price
- Renting Days
- Daily Rate
Splitting these three things into individual functions makes your code much simpler.
public decimal GetBasePrice()
{
return
radioButtonElectric1.Checked ? 60 :
radioButtonElectric2.Checked ? 80 :
radioButtonGas1.Checked ? 55 :
0;
}
public int GetRentingDays()
{
return
radioButtonADay.Checked ? 1 :
radioButtonThreeDays.Checked ? 3 :
radioButtonSevenDays.Checked ? 7 :
radioButtonFourteenDays.Checked ? 14 :
0;
}
public decimal GetDailyRate()
{
return
radioButtonElectric1.Checked ? 20 :
radioButtonElectric2.Checked ? 30 :
radioButtonGas1.Checked ? 25 :
0;
}
In the end the final code is much simpler:
decimal subTotal = GetBasePrice() + GetRentingDays() * GetDailyRate();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hijinxbassist |
