我正在创建一个计算器应用程序,并且尝试将业务逻辑与 UI 分离,以提高代码的可维护性并允许进行更好的单元测试。
我创建了一个 CalculatorUI 类,用于管理用户单击应用程序中的各种按钮时发生的情况。
我还创建了一个 Calculator 类来执行数学运算,并根据用户要求对计算结果进行一些验证。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;
}
}