Nesting is unavoidable, however in most cases returning early is a more viable option.
Consider the following snippet:
MyRoutine(argument)
{
if (0 == argument) {
SubRoutine(argument);
} else if (1 == argument) {
SubRoutineForSomething(argument);
} else {
SubRoutineForMe(argument);
}
return this;
}
I find myself constantly refactoring that to
MyRoutine(argument)
{
if (0 == argument) {
SubRoutine(argument);
return this;
}
if (1 == argument) {
SubRoutineForSomething(argument);
return 1;
}
SubRoutineForMe(argument);
return this;
}
Only exception is to keep things DRY, so instead of
MyRoutine(argument)
{
if (0 == argument) {
SubRoutine(argument);
AnotherAction();
return this;
}
if (1 == argument) {
SubRoutineForSomething(argument);
AnotherAction();
return 1;
}
SubRoutineForMe(argument);
AnotherAction();
return this;
}
I'd rather use
MyRoutine(argument)
{
if (0 == argument) {
SubRoutine(argument);
} else if (1 == argument) {
SubRoutineForSomething(argument);
} else {
SubRoutineForMe(argument);
}
AnotherAction();
return this;
}
Are there any major disadvantages to exiting early? I'm moving from serverside work towards game development (Javascript and C-like languages). Are there any pitfalls I should watch out for/benefits I'm missing (branch prediction)?
I hope this is different than this question.