Bird
Raised Fist0

What will be the output of the following code snippet that uses a Repository pattern?

medium๐Ÿ“ Analysis Q5 of Q15
LLD - Advanced LLD Concepts
What will be the output of the following code snippet that uses a Repository pattern?
class UserRepository:
    def __init__(self):
        self.users = {}
    def add(self, user):
        self.users[user.id] = user
    def get(self, user_id):
        return self.users.get(user_id)

class User:
    def __init__(self, id, name):
        self.id = id
        self.name = name

repo = UserRepository()
user1 = User(1, 'Alice')
repo.add(user1)
print(repo.get(1).name)
A1
BAlice
CNone
DError
Step-by-Step Solution
Solution:
  1. Step 1: Add user to repository

    User with id 1 and name 'Alice' is added to users dictionary.
  2. Step 2: Retrieve user by id and print name

    repo.get(1) returns the User object; printing .name outputs 'Alice'.
  3. Final Answer:

    Alice -> Option B
  4. Quick Check:

    Repository returns stored user by ID [OK]
Quick Trick: Repository stores and retrieves entities by ID [OK]
Common Mistakes:
MISTAKES
  • Expecting None if user exists
  • Printing user ID instead of name
  • Assuming get returns error if key exists

Want More Practice?

15+ quiz questions ยท All difficulty levels ยท Free

Free Signup - Practice All Questions
More LLD Quizzes