[英]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.