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

I would say it is a matter of personal preference. However, first and foremost whichever thing you prefer should be codified in your project's style guide. Consistency trumps everything else by a large margin.

My personal opinion is that this is an excellent use of the ternary operator. When writing software, you want your code to be as simple and short as possible provided it is readable[1]. I find both of them to be equally readable, therefore I prefer the shorter one by a lot. We are talking about 5 lines of code vs 1, which can really add up if this appears commonly all over your codebase. One limited asset every engineer has is monitor real estate, and the more code you can fit on your screen, the better (provided all of that code is the readable variety).

I also find in this particular example, the ternary could get a slight nod for readability as well. This is because with the ternary operator, you start with:

value =

Ok, value is getting assigned to something... then you read the ternary expression. If you are grepping through this code and looking to see what value might be set to, you get to this line and you know you have found it, then you parse the rest of it to figure out what it is being set to.

With the other example, your grepping will lead you to a "value =" that is within a conditional, so now you have to look up and down and explore a little more to see what it might be set to. This is because the ternary operator can only do one small thing, whereas the if statement can do lots of things. Since you are only doing the simple thing, using the simplest possible operator to do that in some sense helps future people reading the code [2].

[1] Which might seem like a spectrum, but I think of it as much more binary. Code is either readable or it isn't. This might seem strange, but my fellow engineers and I spend quite a bit of time grading code submissions to our programming challenges, and of course the "readability" of the code is a key thing we grade for. I think we probably match up our independent up or down votes on readability at least 90% of the time.

[2] If you want to frustrate experienced engineers, have them look through a bunch of code that hasn't been factored down to its simplest form. This is extremely common among inexperienced engineers who refactor code and don't delete a bunch of cruft that now exists due to code or logic changes because "who cares? the code works!", and you get stuff like this:

  if ($has_phone_number) {
      return TRUE;
  } else if ($has_phone_number || $has_email_address) {
      return TRUE;
  } else if (!$has_phone_number) {
      return FALSE;
  } else {
      return FALSE;
  }

  return FALSE;
ahhhh!


$ git diff --stat

1 file changed, 1 insertions(+), 10 deletions(-)




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

Search: