Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for refactoring methods [closed]

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

like image 571
user829174 Avatar asked Dec 07 '11 14:12

user829174


1 Answers

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;
}
like image 125
mqp Avatar answered Nov 09 '22 01:11

mqp