我正在創建一個計算器應用程序,我試圖從UI中分離業務邏輯以改進代碼可維護性並允許更好的單元測試。如何從用戶界面分離業務邏輯
我創建了一個CalculatorUI類來管理用戶單擊應用程序中的各個按鈕時發生的情況。
我也創建了一個計算器類來執行數學計算,並根據用戶需求對計算結果進行一些驗證。 CalculatorUI創建Calculator類的一個實例,並調用Calculator類中的函數來響應用戶點擊。我的問題是,在Calculator類中,如何編寫清除文本框並顯示消息框以使用戶意識到無效結果的代碼?
我是編程新手,根據我的一位同事(高級程序員)的說法,最好將UI與業務邏輯和數據庫分開。
我得到的錯誤狀態'txtDisplay'和'resultValue'在當前上下文中不存在...另外,我應該如何使用bool變量?
這是我的計算器類代碼:
class Calculator
{
public double Addition(double value1, double value2)
{
double result = 0;
result = value1 + value2;
return result;
}
public double Subtraction(double value1, double value2)
{
double result = 0;
result = value1 - value2;
return result;
}
public double Multiplication(double value1, double value2)
{
double result = 0;
result = value1 * value2;
return result;
}
public double Division(double value1, double value2)
{
double result = 0;
result = value1/value2;
return result;
}
public bool CalculationValidation(double result)
{
bool isValid;
bool isFalse;
// determine if the initial result is within the specified range
if ((result < -4000000000) || (result > 4000000000))
{
MessageBox.Show("The result is too large or small to be displayed.");
txtDisplay.text = "0";
resultValue = 0;
return;
}
// round the result if necessary
string test = result.ToString();
if (test.Contains("."))
{
test = (Math.Round(double.Parse(test), 10 - test.Split('.')[0].Count())).ToString();
}
else if (test.Length > 10)
{
test = (Math.Round(double.Parse(test), 10).ToString());
}
txtDisplay.Text = test;
}
}