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

  function getOddness(n: number):
    return (n % 2 === 0)
      ? "Even"
      : "Odd";
Lowest boilerplate makes it the most readable. If working in a language with the ternary operator it ought to be easily recognized!


I love code golf as much as anyone, not sure it's worth it on such small methods tho. Any of the propositions would be fine. Anyway:

    def oddness(n):
      return ["Even", "Odd"][n % 2]
BTW this trick with replacing if-then-else with a lookup is sometimes very useful. Especially if there's many ifs.


Or your write in APL


This is, IMHO, the idiomatic way to do so.


Since the article was in JavaScript:

  const getOddness = (n) => (
    n % 2
      ? 'Odd'
      : 'Even'
  )
Even less visual noise


    const getOddness = n => n % 2 ? 'Odd' : 'Even'


While this is simple and all, the English words if/else don’t require the reader to know the ?: convention. Depending on what background the reader may have, they could think of the set notation where it could mean “all the evens such that odd is true” which makes no sense. Its also very close to a key:value set notation. If/else leave no doubts for the majority of readers. It’s more inclusive if you will.


That's why I gave the caveat that if using a language with the ternary operator, one should know that operator. Python tried using English words for a ternary, but I think that's awkward from a readability perspective. A limited set of symbolic syntax improves readability over using words in my opinion, there's less text to scan.


Learning the basic operators of the language seems like table stakes.

Choosing one of world's spoken languages over others seems to be the opposite of inclusive.


Putting “return” on a different line from the actual value you’re returning?


If there are two ways to say something, then people will find ways to make their choice of method into speech as well.

To me and my style of coding, there's a difference of intent between the two. A ternary connotes a mere computation, something that should have no side-effects. A conditional connotes a procedure; the arms of the conditional might be expected to have side-effects. (And the case of `if (_) return` or similar are pure control flow guards; they neither compute a value nor perform a procedure as such.)

It's not just about where the symbols go on the screen.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

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

Search: