I am wondering what would be the the best practice for refactoring code that looks like this:
Where should the exit criteria should be set and what is the best practice
private static bool Foo()
{
bool result = false;
if (DoMehod1())
{
if (DoMehod2())
{
if (DoMethod3())
{
result = true;
}
else
{
Console.WriteLine("DoMethod3 Failed");
}
}
else
{
Console.WriteLine("DoMethod2 Failed");
}
}
else
{
Console.WriteLine("DoMethod1 Failed");
}
return result;
}
Thanks
The best structure for that code without changing what it does is this:
private static bool Foo()
{
if (!DoMethod1())
{
Console.WriteLine("DoMethod1 Failed");
return false;
}
if (!DoMethod2())
{
Console.WriteLine("DoMethod2 Failed");
return false;
}
if (!DoMethod3())
{
Console.WriteLine("DoMethod3 Failed");
return false;
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With