[英]How can I refactor my if-else statement?
好吧,我在这里为我的计算器准备了一个代码,但是看起来很乱。
这里的逻辑是,当显示等于0时,下一个输入将替换显示,除了0本身。 只需尝试查看此图像即可。 https://www.dropbox.com/s/qtec2r6mcsmjvvt/refactor.jpg?dl=0
private void btn1_Click(object sender, EventArgs e)
{
num = btn1.Text;
if (isEqual)
{
if (operator_pressed == true)
{
if (expr.EndsWith("0"))
{
tbScreen.Clear();
tbScreen.Text += num;
expr = expr.Remove(expr.Length - 1, 1);
expr += num;
}
else
{
tbScreen.Clear();
expr = "";
tbScreen.Text += num;
expr += num;
}
}
else
{
if (tbScreen.Text == "0")
{
tbScreen.Clear();
tbScreen.Text += num;
expr += num;
}
else
{
tbScreen.Clear();
expr = "";
tbScreen.Text += num;
expr += num;
}
}
}
else {
if (operator_pressed == true)
{
if (expr.EndsWith("0"))
{
tbScreen.Clear();
tbScreen.Text += num;
expr = expr.Remove(expr.Length - 1, 1);
expr += num;
}
else
{
tbScreen.Clear();
tbScreen.Text += num;
expr += num;
}
}
else
{
if (tbScreen.Text == "0")
{
tbScreen.Clear();
tbScreen.Text += num;
expr += num;
}
else
{
tbScreen.Text += num;
expr += num;
}
}
}
isEqual = false;
operator_pressed = false;
btnEqual.Focus();
}
希望能得到积极的回应!
首先,您应该改进变量的命名。 尚不清楚此方法的目的是什么。 我只能建议您正在创建某种计算器。 当你编写代码的商业价值应该清楚,当你问到重构代码,您应该解释您的代码应在业务方面做什么 。 例如
我希望能够输入数学表达式“ 1 + 5-2”,然后按“等于”按钮时,我应该在计算历史记录中看到计算结果和表达式。 此方法计算表达式结果并更新控件。 operator_pressed是一个标志,在用户按下某个操作员按钮时设置。 等等
在不知道您的代码用途的情况下,我只能专注于删除重复项。 但是对于其他开发人员来说,意图仍然不是很清楚。 您当前的所有代码都可以简化为
num = btn1.Text;
if (IsInputStarted)
tbScreen.Clear();
if (IsExpressionStarted)
expr = "";
if (operator_pressed && expr.EndsWith("0"))
expr = expr.Remove(expr.Length - 1, 1);
tbScreen.Text += num;
expr += num;
isEqual = false;
operator_pressed = false;
btnEqual.Focus();
用两个属性(或您可以使用的方法)提取。 一个检查是否应该清除屏幕:
private bool IsInputStarted
{
get { return isEqual || operator_pressed || tbScreen.Text == "0"; }
}
第二步验证是否应清除当前表达式
private bool IsExpressionStarted
{
get
{
if (!isEqual)
return false;
if (operator_pressed)
return !expr.EndsWith("0");
return tbScreen.Text != "0";
}
}
进一步的建议 -不要将您的UI代码(UI控件,UI事件)与业务逻辑混合在一起。 这些东西应该分别存在和改变。 我建议您创建某种Calculator
类,该类负责进行计算和存储表达式。 你的代码看起来像
private void EqualsButton_Click(object sender, EventArgs e)
{
double result = calculator.ExecuteExpression();
resultsTextBox.Text = result.ToString();
historyListBox.Items.Add(calculator.Expression);
}
在您的情况下,我建议您为每个要执行的操作考虑一个条件。
您何时要执行tbScreen.Clear()
?
if (isEqual || operator_pressed || tbScreen.Text == "0" )
tbScreen.Clear();
您何时要执行tbScreen += num;
? -总是,所以只要写
tbScreen += num;
您何时要执行expr = "";
?
if (isEqual && ((operator_pressed && !expr.EndsWith("0")) || (!operator_pressed && tbScreen.Text != "0"))
expr = "";
等等..
您将变得更短,更容易忽略代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.