Skip to content

Comment on Ask HN: Do you follow the positive or negative pattern when programming?

Comments

In personal projects I do whatever has the code outside of the `if` block longer. e.g.

    function login() {
      if (isLoggedIn) {
        return
      }
      if (!isAuthenticated) {
        throw AuthenticationFailure
      }
      // Do the login
      ...
    }
It doesn't matter that `isLoggedIn` is positive and `isAuthenticated` is negative, the point is both of those are short-circuit cases.

Though what usually actually ends up happening is

    function login() {
      if (isLoggedIn) {
        return
      } else if (isAuthenticated) {
        doTheLogin()
      } else {
        throw AuthenticationFailure
      }
    }
    

    function doTheLogin() {
      ...
    }
Where there's no "long case", so the order really doesn't matter and I just make everything positive.
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.