Hacker News new | past | comments | ask | show | jobs | submit login

At this point in my coding life (15 years in), I'm pretty strongly against if / else clauses. The readability of such code just plummets in my view.

I try to limit my conditionals to inline statements:

  $x = $y if $b;
Often joined with early returns:

  return $b if $a;
If I find myself coding an if/else branch, that's often a clue that I should refactor this chunk into a function that can use early returns to avoid nested conditionals:

so

  if ($a == FOO) {
    $c = $d;
    }
  else if ($a == BAR) {
    $c = $e; 
    }
  else {
    $c = $f;
  }
becomes

  $c = get_val($a);

	...

  sub get_val {
   my ($a) = @_;
   return $d if $a == FOO;
   return $e if $a == BAR;
   return $f;
   }

Thankfully much of my coding lately is in perl, which lets me use postfix "if/unless" as well as "and/or" to avoid having to use braced conditionals.

I also love myself the ternary operator. Basically my take comes down to "use conditionals for one-line assignments only, NOT for block execution".




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

Search: