Reputation: 337
I am creating a calculator application, and I am trying to separate the business logic from the UI to improve the code maintainability and to allow for better unit tests.
I have created a CalculatorUI class that manages what happens when a user clicks on the various buttons in the application.
I have also created a Calculator class that performs the math, and does some validation on the result of the calculation based on the users requirements. the CalculatorUI creates an instance of the Calculator Class and calls functions in the Calculator Class to respond to the users clicks. My question is, in the Calculator class, how do I write code that clears the textbox and displays a messagebox to make the user aware of the invalid result?
I am new to programming, and according to one of my colleagues ( a senior level programmer) it is best practice to keep the UI separate from the Business Logic and Database.
The errors I am getting state that 'txtDisplay' and 'resultValue' don't exist in the current context... Also, how should I use the bool variables?
Here is my code in the Calculator Class:
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;
}
}
Upvotes: 1
Views: 1489
Reputation: 161
You could raise an exception in the calculator class, and then catch it in your UI and do the reset and show the message. Showing the message and setting the display to 0 is UI logic. That's a nice way to separate in this case.
This way, your UI is dependent on the business logic (Calculator class), but the Calculator class has no knowledge about the UI. The aim should be that all dependencies should point inwards, towards your domain objects.
For separating more complex domains, I would suggest looking into the Facade, Command and Observer patterns.
Upvotes: 1