logoalt Hacker News

metabageltoday at 5:01 PM2 repliesview on HN

In what context can you avoid branches?


Replies

thornewolftoday at 7:59 PM

some initial function like

  v = setup()
  if v == 1:
    side_effect_1()
  elif v > 1:
    side_effect_1()
    side_effect_2(v)
  else:
    raise Exception()
then we can "refactor"

  v = setup()
  if v < 1:
    raise Exception()
  
  side_effect_1()
  if v > 1:
    side_effect_2(v)
i know that this might seem "dumb" that the code was ever setup the first way but code can grow into that shape pretty easily. this refactor "removes" the v==1 branch. this new code also follows the "early return" pattern, which improves readability.
lscharentoday at 5:06 PM

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;
show 2 replies