Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which syntax is better for return value?

I've been doing a massive code review and one pattern I notice all over the place is this:

public bool MethodName()
{
    bool returnValue = false;
    if (expression)
    {
        // do something
        returnValue = MethodCall();
    }
    else
    {
        // do something else
        returnValue = Expression;
    }

    return returnValue;
}

This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?

I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.

like image 652
Omar Kooheji Avatar asked Dec 30 '22 10:12

Omar Kooheji


2 Answers

A lot of people recommend having only one exit point from your methods. The pattern you describe above follows that recommendation.

The main gist of that recommendation is that if ou have to cleanup some memory or state before returning from the method, it's better to have that code in one place only. having multiple exit points leads to either duplication of cleanup code or potential problems due to missing cleanup code at one or more of the exit points.

Of course, if your method is couple of lines long, or doesn't need any cleanup, you could have multiple returns.

like image 174
Franci Penov Avatar answered Jan 02 '23 00:01

Franci Penov


I would have used ternary, to reduce control structures...


return expression ? MethodCall() : Expression;

like image 28
mmattax Avatar answered Jan 02 '23 00:01

mmattax