Ch.1: Design Patterns: When Should Strategy Replace If-Else?
Outline
- 0:00 When should Strategy replace a conditional?
- 0:21 Read the original checkout
- 1:24 The roles in Strategy
- 1:54 Pass a function to checkout
- 3:26 Add the promotion
- 4:15 Configure a function
- 4:35 Make the same edit in both designs
- 5:25 Selection and behavior checks
- 6:15 How the closure keeps its settings
- 6:48 When an object helps
- 7:58 Return a fee, not the whole bill
- 8:27 Choose the simpler design
Transcript
0:00 Design patterns describe reusable ways to organize code. Strategy separates a changing calculation from the code using it. Does that separation earn the extra calls and tracing cost? We'll compare a checkout conditional, passed functions and an object's method. A delivery offer changes, and either design may need one number edited. Let's see what those extra calls buy. Before changing the design, read the original checkout. Pickup adds nothing; standard delivery adds 500 cents. Both paths reach the same final addition.
0:30 And if that name matches neither branch? The unknown-name branch raises an error; it doesn't choose a default. Amounts use whole cents, while the delivery name is text. The key explains Python's notation. Follow that standard-delivery path. For example, a customer orders 4,000 cents of items and chooses standard. The 500-cent fee brings the total to 4,500. Right. The rule will supply the delivery charge, but checkout still owes us the whole bill. Now suppose different developers will change promotional delivery rules independently. The first campaign offers free delivery at 5,000 cents, with the usual fee below that.
1:07 I'd still consider another branch. This requirement doesn't automatically make the conditional bad; the question is whether those policy edits should keep landing inside checkout. Agreed. The visible orders show what's changing: how we calculate the fee. Adding that fee to the subtotal stays the same. That policy change points to Refactoring Guru's Strategy roles. Checkout is the context: surrounding code using an interchangeable strategy, our fee calculation. The references are linked in the description.
1:35 With a specific agreement between them: subtotal in, delivery fee out. We can test an alternative against that job before deciding where to plug it in. My first thought is to extract the changing calculation. But a fixed helper alone isn't enough; the caller needs to supply different behavior. Let's try that. Now give checkout that operation as its second input. A function can be passed as a value and called later by the code receiving it. Wait, are we passing the function or calculating the fee before checkout starts?
2:06 The function itself. Checkout receives it; the highlighted call runs it there. The annotation describes an integer input and result, not the calculation's meaning. Now the two existing rules can fill that input. Pickup ignores the subtotal and returns 0; standard returns 500. Either fits the slot. We haven't earned a folder full of shipping classes; the caller just needs to choose a function. For instance, compare this 4,000-cent order on both paths. The new checkout asks standard for the fee instead of choosing it.
2:37 The comparison ends at the same total. Follow the return arrow: the rule returns 500; checkout performs the addition. So checkout doesn't need a delivery label anymore. It needs the calculation, whoever selected it. But someone still has to turn the customer's delivery name into one of those functions. Where does that happen? Before checkout runs, the application picks the rule. That's assembly: putting the chosen pieces together. So we moved a decision. If a promotion changes, couldn't I just edit its number inside checkout? You could.
3:08 Keeping policy edits out of checkout can matter when different developers own them. But we still need selection, and readers follow another call. Then a fair comparison needs the same order, rules and untouched campaign on both sides. We can judge the benefit against that added call. Now add the promotion we're going to change. Its highlighted condition includes equality: qualifying baskets pay nothing for delivery, while smaller ones pay 500. So we still have a conditional, just inside the behavior that needs it.
3:39 Yes. We weren't trying to ban branches. This policy can change without editing the addition or either earlier rule; we also add its name to the lookup table. Let's test that condition with neighboring inputs. 1 cent below the threshold still pays delivery, producing the larger total on the left. While exactly 5,000 gets free delivery. Adding 1 cent of merchandise drops the amount to pay by 499 cents. Oh, that would make me recheck the total. The drop follows our fictional promotion; these neighboring cases catch a threshold that starts a cent late.
4:14 With the promotion's two settings, this setup operation makes a function using them. Those values stay with the returned function. Does it calculate delivery now, or wait for an order? Only on the later order call. With a 4,000 subtotal, the rule calculates a fee of 500. Adding it to the merchandise cost leaves 4,500 to pay. In the conditional version, raise the first threshold from 5,000 to 8,000. Keep this order's 6,000 subtotal in view. Predict the charge before we reveal it. I'd expect 500 now. But we still edited one number.
4:49 What did separating the rule save? No fewer numbers here. I'd hesitate to add another call just for that. The direct edit lands inside checkout; let's compare the function setup. In the function version, replace only the first setup's threshold with 8,000. The charge stays at 500. Leave the second campaign alone. Either design charges 500 on this order; checkout returns 6,500, with the peer's fee unchanged. Checkout's body stayed untouched. That can separate the work of the developers changing policies, but reading the total now means following an extra function call.
5:25 That edit still leaves selection. If a request names an unconfigured option, would the lookup silently send it through standard? No. Follow the error route: the lookup raises, so checkout never starts. A named policy needs a lookup entry or explicit application configuration. So that unknown name never becomes a substitute calculation. Standard's known name selects its function; checkout calls it for the fee. For these campaigns, the application supplies the configured functions explicitly. Which order would catch a cutoff that accidentally starts 1 cent late?
5:58 Exactly 8,000 should qualify. The smaller input keeps its 500 fee. Pickup and standard also retain their four expected totals. That's two checks: the changed boundary and the choices we promised to preserve. None of these cases proves every possible input. Now open the helper behind those saved settings. It defines an inner function, then returns that function with the numbers still available. So the outer return gives checkout a function, and the inner return supplies a fee when an order arrives?
6:28 Yes. This is a closure: a function that keeps access to settings from the enclosing call. The threshold and charge stay associated with that particular returned function. That explains why the other promotion kept its price. Each setup call produces an independent function; an order subtotal arrives only when we use it. With the function working, I'm not sure we need another class. What would an object add here? We can inspect its threshold field directly when an order gets a surprising delivery charge. The constructor on screen stores those settings on the instance.
7:03 I think I'd add the object only if inspecting those named fields helps us. Now the fee method reads this object's stored settings. Its highlighted comparison performs the same calculation as our configured function. Then checkout still supplies only the subtotal when it calls that selected method? It does. That method stays attached to its object, as Python's class documentation explains. The saved settings are available when checkout supplies the order amount. Suppose a customer asks about that same order.
7:33 Its subtotal is 6,000; why isn't delivery free? For this first campaign, the object's threshold is 8,000. 6,000 doesn't qualify, so the fee is 500. The function's saved threshold explains the same bill. I wouldn't replace it unless the object's fields make that inspection easier. I'd keep it too. Either form still needs the same fee checks; a different threshold doesn't need a different class. But matching the operation's shape isn't sufficient. Imagine a developer returns an order's final total from a rule that's supposed to supply only its delivery fee.
8:07 Hold on, that could charge for the items twice. Would checkout accept it just because it returns an integer? In this example, yes. Misreading 4,500 as a fee makes checkout charge 8,500. Types alone don't catch that mistake. Test the behavior; don't silently substitute another policy when a rule fails. So, back to the original decision. If those two delivery cases stay stable, I'd keep the conditional. Everything needed to follow it sits together. With independent policy edits, I'd consider the extracted rules.
8:39 We can exercise each one directly, but still have to choose it and check what it returns. A 3rd branch doesn't settle it. No. Independent policy changes have to justify the extra call. First, find the changing behavior. Second, agree what goes in and comes back. Whichever rule we supply, checkout needs a delivery fee. 3rd, keep selection visible. 4th, check each rule's behavior, including boundary cases and what the returned number means. 5th, weigh that added structure against the simpler code.
9:09 A small conditional may still fit; use a function or object when that makes the changing rules clearer. Thanks for listening to Learning Podcasts.