CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 6 of 6 · 2 min read

Exercises

Easy

Easy 1: Find the switch (20 minutes)

In code of your own or an example, find a switch or if chain that picks "which way". Write the name of the interface you would create.

Done when: you have the code location, the interface name and a list of the classes.

Hint

Look for words such as "type", "kind" or "mode" in a condition.

Easy 2: Run the lot (20 minutes)

Type the parking lot code and run checkout(130) with each of the three strategies, and checkout(50) with FreeFirstHour.

Done when: you print 60, 100, 40 and 0.

Hint

Round up the minutes to hours, then multiply.

Easy 3: Name the parts (20 minutes)

For list.sort(Comparator.comparing(Booking::start)), say which part is the context, the strategy and the concrete strategy.

Done when: each of the three parts has a name.

Hint

The comparator is the strategy.

Medium

Medium 1: Payment methods (45 minutes)

Write a PaymentStrategy interface with pay(long amount) and classes for card, UPI and wallet. Write a Checkout context that takes one.

Done when: Checkout has no mention of any payment type, and a fourth type is added without editing it.

Hint

The context method calls strategy.pay(amount).

Medium 2: Config picks the rule (45 minutes)

Build a Map<String, FeeStrategy> and choose a strategy from a string such as "flat". Handle an unknown name with a clear error.

Done when: three names work and an unknown name throws a message that lists the valid ones.

Hint

Map.get returns null for a missing key.

Medium 3: Shared or per use (45 minutes)

Write a strategy that keeps a counter inside it. Share it between two contexts and show the bug. Then move the counter into the context.

Done when: you show wrong counts before and right counts after.

Hint

Pass the count into the strategy as a parameter.

Hard

Hard 1: Pricing with two strategies (90 minutes)

A room booking price depends on a discount rule and a tax rule. Make both strategies and let a PriceCalculator take one of each.

Done when: four combinations work, and adding a new tax rule needs no edit to the calculator.

Hint

Two fields in the calculator, both interface types.

Hard 2: Strategy or subclass (90 minutes)

Solve the parking fee problem twice, once with subclasses of ParkingLot and once with strategies. Add a rule that changes at 6 pm. Compare.

Done when: a table shows classes added, switching at run time, and edits needed for the new rule.

Hint

Count the files touched by the new rule in each version.

Hard 3: Too many strategies (90 minutes)

Take a design with eight strategy classes of three lines each. Decide which to keep as classes, which to make lambdas, and which to remove.

Done when: you give a decision for all eight with reasons and show the shorter code.

Hint

A one-line rule with no state suits a lambda.