C
C#5mo ago
Jason_Bjorn

✅ 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%");

}
2 Replies
Servator
Servator5mo ago
Math.Clamp() ?
Jason_Bjorn
Jason_BjornOP5mo ago
That's not the behavior I want
Want results from more Discord servers?
Add your server