Demo: replacing a type switch with Strategy
On This Lesson 3 topics
The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.
In this lesson
turn a growing switch on shipping type into Strategy. Prepares JNR-005-LAB1.
Draft outline details
Step by step
- Show a
switch (shippingType)inShippingCalculatorwith three cases; tests pass. - Extract the
ShippingStrategyinterface and one class per case. - Choose the strategy through a small factory.
- Planned mistake: create a strategy for a case with one line of code and a new file for each trivial detail; the design is heavier than the switch. Fix: use lambdas for tiny strategies, and keep only the meaningful classes.
- Run the tests; add a fourth shipping type with no edit to old classes.
- Say in one line why Strategy was justified here.
Check your understanding
When is a lambda enough for a strategy?
Show answer
When the behavior is tiny and has no state.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.