I understand that putting a return in the middle of a function is not very
good idea
It is a recommendation to make the code more readable, it is called "single point of exit" ( single exit point ). For example, if you modify a function and make a change, it may be that the change
For example, right now I have debugged an initialization function and, if the value of the configuration was null
, I would do return null;
in the middle of the code because there was nothing to do. Then I added more initialization code that always had to be executed and I left the return
.
It can also affect the debugging facility.
The simplest alternative is to change the flow so that the check implies execution, that is:
function hola() {
if (valor == 0) {
return false;
}
// Hacer hola();
return loquetoque;
}
go to:
function hola() {
if (valor != 0) {
// hacer hola();
return loquetoque;
}
return false;
}
or similar varieties (put the return false
in a else
, put the value to return in a variable and only do a return
, etc.)
In any case, the first thing is the clarity of the code, it is not a rule that must be followed blindly. In particular, making a series of return
at the beginning of the code according to parameter checks can be a better idea.
function hola(par1, par2, par3, par4) {
if (par1 == 0) {
return false;
}
if ((par2 == 1) && (par4 ==5)) {
return false;
}
if (par3 == 2) {
return false;
}
return loquetoque;
// hacer hola
}
before:
function hola(par1, par2, par3, par4) {
if ((par1 != 0) || ((par2 != 1) && (par4 != 5)) || (par3 != 1) {
// hacer hola
return loquetoque;
}
return false;
}