Skip to content
Ameen Abozaid
In reviewJNR-005-L10

Demo: replacing a type switch with Strategy

  • Lesson 10 of 10
  • 11 min read
  • Junior
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

  1. Show a switch (shippingType) in ShippingCalculator with three cases; tests pass.
  2. Extract the ShippingStrategy interface and one class per case.
  3. Choose the strategy through a small factory.
  4. 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.
  5. Run the tests; add a fourth shipping type with no edit to old classes.
  6. 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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Type to search levels, phases, modules and lessons.