Is it considered good practice to use more than one statement return
within the function? for instance:
if ( /* ... */ )
return x;
else
return y;
or do I have to create an auxiliary variable to only make a return at the end of the code with that auxiliary variable?
There is no unified policy on this subject. Each solution has its advantages and disadvantages:
a single return
This solution usually makes function maintenance easier, since for any function you will know both its entry point (at the start of the function) and its exit point (at the end of it).
For the above reason you will see that it is easier to debug the code since to verify what is returned by a function it will require a single stop point.
several returns
This workaround can be used to avoid excessive nesting in the function:
It is easy to see in the previous example that if the number of conditions is relatively high (more than 3 for example) the excessive number of nested braces can hinder the readability of the code.
Its main disadvantage is that debugging a function requires locating all
return
.Personal conclusion
As a general rule try to program the functions with a single
return
. If along with this habit you get used to not writing excessively long functions (more than 30 lines) so much the better.I usually leave the multiple option
return
in those functions in which a series of initial checks are carried out so as not to fill the function with keys. I consider that in this case the use of several exit points is justified since this improves the readability of the code... however, I emphasize that it is my personal opinion.