✅ Improving code
I have this old method and then I didn't like how repetative the logic was so I put it in a lambda. I was wondering is there a better/more c# idomatic way still?
// old method
temp changed by more than 10%
if (Math.Abs(e.NewTemperature - e.OldTemperature) > 0.10)
{
Console.WriteLine("Temperature changed by more than 10%");
}
if (Math.Abs(e.NewHumidity - e.OldTemperature) > 0.10)
{
Console.WriteLine("Humidity changed by more than 10%");
}
// new method
// lambda, static to not capture anything
static bool isWithinPercentage(double value1, double value2, double decimalPercentage) => (Math.Abs(value1 - value2) <= decimalPercentage);
if (!isWithinPercentage(e.NewTemperature, e.OldTemperature, 0.10))
{
Console.WriteLine("Temperature changed by more than 10%");
}
if (!isWithinPercentage(e.NewHumidity, e.OldHumidity, 0.10))
{
Console.WriteLine("Humidity changed by more than 10%");
} // old method
temp changed by more than 10%
if (Math.Abs(e.NewTemperature - e.OldTemperature) > 0.10)
{
Console.WriteLine("Temperature changed by more than 10%");
}
if (Math.Abs(e.NewHumidity - e.OldTemperature) > 0.10)
{
Console.WriteLine("Humidity changed by more than 10%");
}
// new method
// lambda, static to not capture anything
static bool isWithinPercentage(double value1, double value2, double decimalPercentage) => (Math.Abs(value1 - value2) <= decimalPercentage);
if (!isWithinPercentage(e.NewTemperature, e.OldTemperature, 0.10))
{
Console.WriteLine("Temperature changed by more than 10%");
}
if (!isWithinPercentage(e.NewHumidity, e.OldHumidity, 0.10))
{
Console.WriteLine("Humidity changed by more than 10%");
}