4 ms·
In what context can you avoid branches?
by metabagel 18d ago
In what context can you avoid branches?
- lscharen 18d agoMaybe 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;
- metabagel 18d agoOK, or maybe... total = calculateOrderTotal(user.order); total = total * user.discount;
- 1718627440 18d agoOr: total = calculateOrderTotal(user.order); total *= user.discount; or: return calculateOrderTotal(user.order) * user.discount;
- Narishma 18d agoDidn't you just shift the branch to the calculateDiscount() function?
- 1718627440 18d agoNot necessarily. return 1 - user.isPremiumMember * 0.1; would also cut it.
- lscharen 16d agoNo, 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.
- thornewolf 18d agosome 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.
- eikenberry 17d agoEarly returns is one method.