SRP in Action: Parking Lot System Design
Applying SRP to a Real System
A parking lot system requires managing vehicle entry and exit, fee calculation, spot allocation, and payment processing. Without SRP, developers often create a monolithic ParkingLot class that handles everything. Let us see how SRP structures this design cleanly.
Domain Analysis: Identifying Responsibilities
First, Spot Management is responsible for tracking which spots are available and assigning vehicles to appropriate spots based on vehicle type. This changes when spot allocation algorithms change (like switching from first-available to nearest-to-exit).
Second, Fee Calculation is responsible for computing parking charges based on duration, vehicle type, and time of day. This changes when pricing models change (like adding surge pricing or member discounts).
Third, Payment Processing is responsible for handling transactions, refunds, and receipt generation. This changes when adding new payment methods or integrating with different payment gateways.
Fourth, Ticket Management is responsible for issuing and validating parking tickets. This changes when ticket format or security requirements change.
SRP-Compliant Design
- strategy: AllocationStrategy
+ releaseSpot(spotId): void
+ applyDiscount(ticket, coupon): Money
+ refund(transactionId): void
+ validateTicket(ticketId): boolean
+ exitVehicle(ticket, payment): Receipt
How Responsibilities Are Isolated
SpotManager: When business decides to prioritize handicapped parking or reserve spots for electric vehicles, only SpotManager changes. Fee calculation remains untouched.
FeeCalculator: When marketing introduces weekend discounts or peak hour pricing, only FeeCalculator changes. Spot allocation logic is unaffected.
PaymentProcessor: When adding cryptocurrency payments or switching from Stripe to PayPal, only PaymentProcessor changes. Ticket validation continues working.
TicketManager: When security requires QR codes instead of numeric tickets, only TicketManager changes. Fee calculation does not need updates.
The Facade Coordinator
The ParkingLotFacade class coordinates these responsibilities but contains no business logic itself. It orchestrates the workflow: when a vehicle parks, it asks SpotManager for a spot, asks TicketManager to issue a ticket, and returns the result. This facade is optional but useful for providing a simple interface to clients.
Testing Benefits
With SRP, you can test fee calculation without setting up database connections or payment gateways. You can test spot allocation without mocking payment processors. Each class has a focused contract and minimal dependencies, making unit tests simple and fast.