Skip to content

DAY 3 — Extensibility & Failure Handling (SDE-2 Core Signal)

Perfect. ​Day 3 is where you start looking like a strong SDE-2 / early SDE-3 — not just making things work, but making them extendable without rewriting code.
Today’s problems explicitly test:
Open–Closed Principle
Strategy-based design
Failure handling
Clean abstractions
You’ll still code fully, but design quality now matters as much as correctness.

🟠 DAY 3 — Extensibility & Failure Handling (SDE-2 Core Signal)

Concepts Introduced Today (Short + Practical)

1️⃣ Open–Closed Principle (OCP)

Classes should be open for extension, closed for modification.
Bad:
if (type == "FLAT") { ... }
else if (type == "PERCENT") { ... }
Good:
interface DiscountRule {
boolean applicable(Context ctx);
double apply(double price);
}
Interviewers actively watch for this.

2️⃣ Failures Are First-Class Citizens

Production systems:
Fail
Retry
Fallback
Eventually give up
Ignoring failures = ❌ SDE-1 thinking.

✅ Problem 1: Pluggable Discount Engine

📌 Problem Statement

Design a discount engine that applies multiple discount rules to a cart.
Rules:
Each discount decides if it applies
Discounts have priority
Applied in priority order
Easy to add new discounts without changing engine code

Functional Requirements

Input:
Cart total
Cart metadata (userType, coupon, etc.)
Output:
Final discounted price

Discount Rules (Initial)

Flat ₹100 OFF
Applies if cart total ≥ 1000
10% OFF for PREMIUM users
Coupon Discount
₹200 OFF if coupon = "SAVE200"

Example

Cart total = 2000
User = PREMIUM
Coupon = SAVE200

Apply in order:
- Flat 100 → 1900
- 10% → 1710
- Coupon 200 → 1510

🧩 Java Interfaces (DO NOT MODIFY)

public interface DiscountRule {
int getPriority(); // lower number = higher priority
boolean isApplicable(DiscountContext context);
double apply(double currentPrice);
}
public class DiscountContext {
public final double cartTotal;
public final String userType;
public final String coupon;

public DiscountContext(double cartTotal, String userType, String coupon) {
this.cartTotal = cartTotal;
this.userType = userType;
this.coupon = coupon;
}
}
import java.util.List;

public interface DiscountEngine {
double applyDiscounts(double cartTotal, DiscountContext context);
}

🧪 Driver Code (Auto Tests + Edge Cases)

import java.util.*;

public class DiscountEngineTest {

public static void main(String[] args) {
List<DiscountRule> rules = List.of(
new FlatDiscountRule(),
new PremiumUserDiscountRule(),
new CouponDiscountRule()
);

 
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.