| ▲ | metabagel 4 hours ago |
| In what context can you avoid branches? |
|
| ▲ | thornewolf 2 hours ago | parent | next [-] |
| 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. |
|
| ▲ | lscharen 4 hours ago | parent | prev [-] |
| 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;
|
| |
| ▲ | metabagel 4 hours ago | parent | next [-] | | OK, or maybe... total = calculateOrderTotal(user.order);
total = total * user.discount;
| | |
| ▲ | 1718627440 an hour ago | parent [-] | | Or: total = calculateOrderTotal(user.order);
total *= user.discount;
or: return
calculateOrderTotal(user.order)
* user.discount;
|
| |
| ▲ | Narishma 4 hours ago | parent | prev [-] | | Didn't you just shift the branch to the calculateDiscount() function? | | |
| ▲ | 1718627440 an hour ago | parent [-] | | Not necessarily. return 1 - user.isPremiumMember * 0.1;
would also cut it. |
|
|