Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - writing method blocks

Tags:

methods

c#

this is a general question regarding method block structures. Does anyone have an opinion on what is a better way to design methods given the 2 alternatives below?

private void Method1()
{
    if (!A)
    {
        return;
    }

    if (!B)
    {
        return;
    }

    if (!C)
    {
        return;
    }

    // DO WORK.......

    return;
}

private void Method2()
{
    if (A)
    {
        if (B)
        {
            if (C)
            {
                // DO WORK.......

                return;
            }
        }
    }

    return;
}
like image 395
Grant Avatar asked Dec 18 '25 02:12

Grant


1 Answers

I prefer method 1, the "early exit" approach. In my opinion, it's more clear. And I really try to avoid lots of nested 'if' statements.

Also, you can't return 'null' in a void method :)

like image 195
Noon Silk Avatar answered Dec 20 '25 15:12

Noon Silk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!