Programming Practices – Should ‘Else’ Be Used When Control Flow Renders It Redundant?

conditionscontrol flowprogramming practices

I sometimes stumble upon code similar to the following example (what this function does exactly is out of the scope of this question):

function doSomething(value) {
  if (check1(value)) {
    return -1;
  }
  else if (check2(value)) {
    return value;
  }
  else {
    return false;
  }
}

As you can see, if, else if and else statements are used in conjunction with the return statement. This seems fairly intuitive to a casual observer, but I think it would be more elegant (from the perspective of a software developer) to drop the else-s and simplify the code like this:

function doSomething(value) {
  if (check1(value)) {
    return -1;
  }
  if (check2(value)) {
    return value;
  }
  return false;
}

This makes sense, as everything that follows a return statement (in the same scope) will never be executed, making the code above semantically equal to the first example.

Which of the above fits the good coding practices more? Are there any drawbacks to either method with regard to code readability?

Edit: A duplicate suggestion has been made with this question provided as reference. I believe my question touches on a different topic, as I am not asking about avoiding duplicate statements as presented in the other question. Both questions seek to reduce repetitions, albeit in slightly different ways.

Best Answer

I like the one without else and here's why:

function doSomething(value) {
  //if (check1(value)) {
  //  return -1;
  //}
  if (check2(value)) {
    return value;
  }
  return false;
}

Because doing that didn't break anything it wasn't supposed to.

Hate interdependence in all it's forms (including naming a function check2()). Isolate all that can be isolated. Sometimes you need else but I don't see that here.