简体   繁体   English

如何重构if-else语句?

[英]How can I refactor my if-else statement?

Well, I have a code here for my calculator but it seems so messy. 好吧,我在这里为我的计算器准备了一个代码,但是看起来很乱。

The logic here is when the display is equal to 0 the next input well replace the display except for 0 itself. 这里的逻辑是,当显示等于0时,下一个输入将替换显示,除了0本身。 Just try seeing this image. 只需尝试查看此图像即可。 https://www.dropbox.com/s/qtec2r6mcsmjvvt/refactor.jpg?dl=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();
    }

Hoping for a positive response! 希望能得到积极的回应!

First of all, you should improve naming of your variables. 首先,您应该改进变量的命名。 It's not clear what the purpose of this method. 尚不清楚此方法的目的是什么。 I can only suggest that you are creating some kind of calculator. 我只能建议您正在创建某种计算器。 When you write your code business value should be clear, and when you ask to refactor code, you should explain what your code should do in business terms. 当你编写代码的商业价值应该清楚,当你问到重构代码,您应该解释您的代码应在业务方面做什么 Eg 例如

I want to be able to type in math expression "1 + 5 - 2" then when I press 'Equals' button I should see result of calculation and expression in calculation history. 我希望能够输入数学表达式“ 1 + 5-2”,然后按“等于”按钮时,我应该在计算历史记录中看到计算结果和表达式。 This method calculates expression result and updates controls. 此方法计算表达式结果并更新控件。 operator_pressed is a flag which is set when user press some operator button. operator_pressed是一个标志,在用户按下某个操作员按钮时设置。 Etc 等等

Without knowing purpose of your code I can only focus on removing duplicates. 在不知道您的代码用途的情况下,我只能专注于删除重复项。 But intent is still will not be very clear for other developers. 但是对于其他开发人员来说,意图仍然不是很清楚。 All your current code can be simplified to 您当前的所有代码都可以简化为

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();

With two properties (or you can use methods) extracted. 用两个属性(或您可以使用的方法)提取。 One checks whether screen should be cleared: 一个检查是否应该清除屏幕:

private bool IsInputStarted
{
    get { return isEqual || operator_pressed || tbScreen.Text == "0";  }
}

Second verifies whether you should clear current expression 第二步验证是否应清除当前表达式

private bool IsExpressionStarted
{
    get
    {
        if (!isEqual)
            return false;

        if (operator_pressed)
            return !expr.EndsWith("0");

        return tbScreen.Text != "0";
    }
}

Further recommendations - do not mix your UI code (UI controls, UI events) with your business logic. 进一步的建议 -不要将您的UI代码(UI控件,UI事件)与业务逻辑混合在一起。 These things should live and change separately. 这些东西应该分别存在和改变。 I would recommend you to create some kind of Calculator class which will be responsible for making calculations and storing expressions. 我建议您创建某种Calculator类,该类负责进行计算和存储表达式。 And your code will look like 你的代码看起来像

private void EqualsButton_Click(object sender, EventArgs e)
{
   double result = calculator.ExecuteExpression();
   resultsTextBox.Text = result.ToString();    
   historyListBox.Items.Add(calculator.Expression);
}

in your case I would suggest to think of a condition for every single action you want to perform. 在您的情况下,我建议您为每个要执行的操作考虑一个条件。

When do you want to execute tbScreen.Clear() ? 您何时要执行tbScreen.Clear()

if (isEqual || operator_pressed || tbScreen.Text == "0" )
    tbScreen.Clear();

When do you want to execute tbScreen += num; 您何时要执行tbScreen += num; ? - always, so just write -总是,所以只要写

tbScreen += num;

When do you want to execute expr = ""; 您何时要执行expr = ""; ?

if (isEqual && ((operator_pressed && !expr.EndsWith("0")) || (!operator_pressed && tbScreen.Text != "0"))
   expr = "";

and so on.. 等等..

you will get much shorter and easier to overlook code 您将变得更短,更容易忽略代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM