Search code examples
language-agnosticcoding-styleconventions

nested "if"s or more "return" statements?


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;

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.