0

My first windows form app, Kind advise how to write more efficiently. don't know to write for display only two decimal

namespace WindowsFormsApp1 { public partial class Form1 : Form { private const string V = "ok"; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void Button1_Click(object sender, EventArgs e) { double tunelLenght = double.Parse(textBox1.Text); double spacingBetween = double.Parse(textBox2.Text); double result1 = 0; double result2 = 0; string errorMessage1 = "Please Entre the correct specing between, Try again!"; string errorMessage2 = "Tunnel Lenght should be longer than the sapceing between, Try again!"; if (spacingBetween != 0 && tunelLenght > spacingBetween) { if (radioButton1.Checked == true) { result2 = (tunelLenght / spacingBetween) / 2; result1 = (tunelLenght / spacingBetween) - result2; } else if (radioButton2.Checked == true) { result2 = (tunelLenght / spacingBetween) / 3; result1 = (tunelLenght / spacingBetween) - result2; } else if (radioButton3.Checked == true) { result2 = (tunelLenght / spacingBetween) / 4; result1 = (tunelLenght / spacingBetween) - result2; } textBox3.Text = result1.ToString(); textBox4.Text = result2.ToString(); } else if (spacingBetween == 0) { textBox5.Text = errorMessage1; } else if (spacingBetween == 0 || tunelLenght < spacingBetween) { textBox5.Text = errorMessage2; } } } }

29th Apr 2019, 3:06 AM
Kyaw Myo Oo
Kyaw Myo Oo - avatar
2 ответов
+ 1
1) Use meaningful names for variables, objects, methods etc. What radiobutton1 is doing should be clear from its name. 2) DRY aka do not repeat yourself. The only thing that changes in different if clauses is one number so calculation can be done as method and called with different argument in each case. 3) Use switch instead of multiple ifs.
29th Apr 2019, 7:29 AM
Dima Makieiev
Dima Makieiev - avatar
+ 1
Thank for advise.
29th Apr 2019, 7:42 AM
Kyaw Myo Oo
Kyaw Myo Oo - avatar