Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm with Mozilla.

If I have a function with multiple conditions that cause me to return error / false / nil, I'd rather not have to nest them all in a series of if/then/else statements nor combine them into a single more-complicated if condition. I'd rather write them each as separate if-and-returns, followed by the real meat of the function.

function updatePlayers{

  if (charList is empty)
     return false;

  if (play is paused)
     return false;

  if (char is frozen)
     return false;

  //do stuff here
  return true;
}

I think this better spells out the "error" conditions.



Guard clauses are a particular case of if statements. I agree with omitting elses when using guard clauses. A blanket rule that eliminates elses after returns doesn't make any sense.


Blanket rules don't make sense.


You'd be right, of course, but the original article concedes this point. He's talking about situations like

  if (a < b)
    return a
  return b
vs.

  if (a < b)
    return a
  else
    return b
vs

  return ( (a < b) ? a : b)


What is the distinction between those two situations? (i.e. those in which the article "concedes the point"?)


Presuming this is a genuine question: the difference is whether one goes on to do more work after the 'guard' return, or whether one is just choosing which value to return.

I think the style guide is being silly, and there is no simple rule that says "always use an else" or "never use an else". I'd see "Avoid unnecessary indentation" as a better rule.


One's an early return due to error, one's a conditional return value.


Error is the wrong term, because you don't return after an error condition, you raise an exception. Perhaps stop condition is more appropriate?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: