‹ BackHN Continuity

Thread

Small programming tricks

681 points · 294 comments · signa11

  1. winternewt · · focus · HN ↗
    Only a few of these are actual programming tricks. The problem with sharing them is that they'll typically seem obvious to you, since you know them. It's difficult to know what is actually unknown to other people, and if you share stuff everybody knows you risk coming off as arrogant.

    Here's one that I think more people should know: avoid branches. If I can do the same thing without an if statement and even a logical expression, the code typically both becomes easier to understand for people and easier to run for the CPU.

    1. cachvico · · focus · HN ↗
      I'm struggling to comprehend how branches can be avoided (or why one would want to, as they are the cornerstone of programming). I can only think how to obfuscate them, which is rarely useful.
      1. corps_and_code · · focus · HN ↗
        Maybe they mean rather than:

        if (thingThatIsTrue):

          // a bunch of logic here...
        
        else:

          // different logic here...
        
        
        they mean:

        if (thingThatIsTrue):

          return doThisWhenTrue()
        
        return dothisWhenFalse()

        Just a simple example. I'm not sure if this is what you consider "obfuscating" the branches. Logically the same, but a bit more linear to understand?

        Edit: I am bad at formatting comments here.

        1. taink · · focus · HN ↗
          Putting two spaces before the line formats is as code.

          Example:

          No space before start of line.

          One space before start of line.

            Two spaces before start of line.
          
          Thus, you can put multiple lines of code with indentation as well as long as you put two spaces at the start of the line:

          int main() { return 0; }

            int main() {
              return 0;
            }
          
          See <a href="https:&#x2F;&#x2F;news.ycombinator.com&#x2F;formatdoc">https:&#x2F;&#x2F;news.ycombinator.com&#x2F;formatdoc
          1. corps_and_code · · focus · HN ↗
            Oh perfect, thanks!
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.