MediumPro challengePython

Dependency Inversion Principle

PythonClean CodeSOLIDDIP

High-level modules should not depend on low-level modules — both should depend on abstractions.

# dirty — UserService is hardcoded to MySQLUserRepo
class MySQLUserRepo:
    def __init__(self, db):
        self.db = db
    def find_by_id(self, user_id):
        return self.db.get(user_id)

class UserService:
    def __init__(self):
        self.repo = MySQLUserRepo({})  # hardcoded!
    def get_user(self, user_id):
        return self.repo.find_by_id(user_id)

Refactor `solve(db, user_id)`: instead of hardcoding the repo, create a simple in-memory repo from db (a plain dict) and look up user_id. The point: solve receives its data source — it doesn't instantiate one.

solve({'u1': {'id': 'u1', 'name': 'Alice'}}, 'u1'){'id': 'u1', 'name': 'Alice'}

Sample tests

Test #1Finds existing user
Input: [{"u1":{"id":"u1","name":"Alice"}},"u1"]
Output: {"id":"u1","name":"Alice"}
Test #2Multi-entry db, correct lookup
Input: [{"u2":{"id":"u2","name":"Bob"},"u3":{"id":"u3","name":"Carol"}},"u3"]
Output: {"id":"u3","name":"Carol"}
Test #3Missing id returns None
Input: [{"u1":{"id":"u1","name":"Alice"}},"u99"]
Output: null