Card 04/ 05
All 5 cards
ExerciseDifficulty: Beginner1 min
Rewrite This Constructor
FareCalculator below builds its own pricing client. Rewrite it so the client is handed in through the constructor instead, the way RideService and NotificationService were.
class FareCalculator {
private final LiveSurgePricingClient pricingClient = new LiveSurgePricingClient();
double fareFor(String zone, double baseFare) {
return baseFare * pricingClient.surgeMultiplierFor(zone);
}
}See a fix
interface PricingClient {
double surgeMultiplierFor(String zone);
}
class LiveSurgePricingClient implements PricingClient {
public double surgeMultiplierFor(String zone) { /* calls a real pricing service */ return 1.0; }
}
class FareCalculator {
private final PricingClient pricingClient;
FareCalculator(PricingClient pricingClient) {
this.pricingClient = pricingClient;
}
double fareFor(String zone, double baseFare) {
return baseFare * pricingClient.surgeMultiplierFor(zone);
}
}A test can now pass new FareCalculator(zone -> 1.4) and check fareFor("downtown", 10.0) comes to 14.0 — verified: it does — without a pricing service running anywhere.