‹ 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. metabagel · · focus · HN ↗
      In what context can you avoid branches?
      1. lscharen · · focus · HN ↗
        Maybe something (contrived) like this providing no-op defaults?

          total = calculateOrderTotal(user.order);
          if (user.isPremiumMember) {
            total = total * 0.9;        // 10% discount
        
        versus

          total = calculateOrderTotal(user.order);
          discount = calculateDiscount(user);  // Returns 0.9 or 1.0
          total = total * discount;
        1. Narishma · · focus · HN ↗
          Didn't you just shift the branch to the calculateDiscount() function?
          1. 1718627440 · · focus · HN ↗
            Not necessarily.

               return 1 - user.isPremiumMember * 0.1;
            
            would also cut it.
          2. lscharen · · focus · HN ↗
            No, because the point is that the branch version does not touch "total" when the branch is taken, but the non-branch version will always multiply "total" by something.
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.