How can I reduce the amount of code without losing quality?
Well... there is no quality yet ;-) and actually you are going to gain some code if you want to improve it.
I won't try to prove whether there are numbers that can break this fraction in any way but for the sake of the review let's assume the denominator can be zero.
The first improvement you can make is to create a class and a method for the formula because in a real application you wan't to write some test before you let anyone use it so how about a Calculator
? I don't know if this formula has any special name so I just named it Fraction1
.
Apart from putting it in a testable calculator you should work on the names. What is z
or w
? How are those letters related to the formula? If you are splitting it into multiple variables then give them resonable names.
Should it happen that the denominator is 0
then the DivideByZeroException
is to be thrown and handeled.
class Calculator
{
public double CalcFraction1(double x, double y)
{
var numerator = Math.Abs(x) - Math.Abs(y);
var denominator = (1 + Math.Abs(x) * Math.Abs(y));
if (denominator == 0)
{
throw new DivideByZeroException();
}
return numerator / denominator;
}
}
You now have a calculator that works. The next step is to read from the console... but maybe you want to read the numbers until the input is correct? Currently it would crash if you enter a letter. So create a helper for it that will try to parse the input until it's a valid value. Instead of using int
for this job you could use double
to get more precision:
private static double ReadNumber()
{
double value;
while (!double.TryParse(Console.ReadLine(), out value)) { }
return value;
}
The last step is to put everything together, this is, create the calculator, read the the numbers and calculate the result or handle the exception if it wasn't possible:
void Main()
{
var calculator = new Calculator();
Console.WriteLine("Please, enter two numbers");
var x = ReadNumber();
var y = ReadNumber();
try
{
Console.WriteLine($"W = {calculator.CalcFraction1(x, y)}");
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot calculate fraction1 because the denominator is zero.");
}
}
You should always try to encapsulate pieces of code that should be tested or can work and be reused independently for example you could copy/paste the ReadNumber
method and use it for a different console application or tune it and add additional output about an invalid number without touching any other part. This is what we always try to achieve. Small units that do their job well and can be use like pieces of puzzle to build something bigger, something useful.