SOLIDL2 · Easy
DIP: Decouple the Database Layer
Problem
UserService directly instantiates MySQLDatabase inside its constructor: `this.db = new MySQLDatabase()`. This means switching to PostgreSQL requires editing UserService. Testing UserService requires a real database. Apply Dependency Inversion — high-level modules should not depend on low-level modules; both should depend on abstractions.
Requirements
- IUserRepository interface with: findById(id), save(user), delete(id)
- MySQLUserRepository implements IUserRepository
- PostgreSQLUserRepository implements IUserRepository (same contract)
- UserService accepts IUserRepository in its constructor (constructor injection)
- Show how to swap database without touching UserService
- Show how to inject a MockUserRepository in tests
Constraints
- –UserService must not import or reference MySQLUserRepository or PostgreSQLUserRepository
- –All dependencies must be injected — no new inside UserService
✓ Saved