Question

I would like to know which is better in a function (in my case a java method, but I assume it is applicable in more langauges): including nested ifs with few return statements, or no nested ifs with many return statements?

For the sake of brevity, I'll use a simple example; However, I am asking about a general and longer case for both options.

if(condition1) {
      if(condition2) {
         return condition3;
      }
}
return false;

or this:

if(!condition1) 
  return false;
if(!condition2)
   return false;
return condition3;
Was it helpful?

Solution

I prefer the "return often" method, especially for complicated condition-checking functions. To me, this looks a lot clearer:

if (foob || bar) {
    return "morgan";
}
if (!glorb) {
    return "noglorb";
}
if (argutan) {
    return "gahx!";
}
return "nurb";

Than even:

if (foob || bar) {
    res = "morgan"
}
else {
    if (!glorb) {
        res = "noglorb";
    }
    else {
        if (argutan) {
            res = "gahx!";
        }
        res = "nurb";
    }
}
return res;

Further, if I find something like the latter beginning to form in a longer function, then I'll put that code in a new function just so I can use the "return often" style.

OTHER TIPS

The first method is typically better when you begin going onto higher orders of switches.

Imagine your CPU running through a simple if check of n-1 conditions vs failing condition k (1

If you're parsing a database for 1000 conditions and fail on condition 15 then you're in for a lot of "useless" computations, just to realize my notation with an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top