पाठ 5 / 25

SOLID Applied Briefly

Five principles in interview terms.

What each letter means in practice

Single responsibility: a class has one reason to change (pricing is separate from ticket storage). Open/closed: add behaviour by adding classes, not by editing a growing if/else (a new vehicle type adds a class). Liskov substitution: subtypes must work wherever the base type is expected without surprises. Interface segregation: prefer small interfaces (Payable, Refundable) over one fat interface. Dependency inversion: high-level code depends on abstractions, and concrete implementations are injected. In interviews, mention a principle when it drives a decision, not as a list.

Open/closed and dependency inversion together

Java sketch.

interface PricingStrategy {
    long priceInCents(Ticket ticket, java.time.Instant exitTime);
}

class HourlyPricing implements PricingStrategy {
    public long priceInCents(Ticket t, java.time.Instant exit) {
        long hours = Math.max(1, java.time.Duration.between(t.entryTime(), exit).toHours());
        return hours * 200;   // assumed rate: 2.00 per hour
    }
}

class CheckoutService {
    private final PricingStrategy pricing;      // depends on the abstraction
    CheckoutService(PricingStrategy pricing) { this.pricing = pricing; }
    long checkout(Ticket t, java.time.Instant exit) { return pricing.priceInCents(t, exit); }
}

Do not recite the acronym

Interviewers credit applying a principle to a concrete choice far more than listing all five definitions.

त्वरित जाँच: Adding a new pricing rule by writing a new class rather than editing existing ones follows which principle?

  • Liskov substitution
  • Open/closed
  • Interface segregation
  • Single table inheritance
Answer

Open/closed — Open for extension, closed for modification.