Sobes.tech
Junior — Middle

Have you used the Repository pattern for database interaction in your projects?

sobes.tech AI

Answer from AI

Yes, the Repository pattern is often used to abstract data access and simplify testing. The Repository acts as a layer between the business logic and the data source (e.g., a database), providing a unified interface for CRUD operations.

Here's an example of a simple repository in Python using SQLAlchemy:

class UserRepository:
    def __init__(self, session):
        self.session = session

    def get_by_id(self, user_id):
        return self.session.query(User).filter(User.id == user_id).first()

    def add(self, user):
        self.session.add(user)
        self.session.commit()

    def list_all(self):
        return self.session.query(User).all()

This approach helps isolate database logic and makes it easier to replace the data source without changing the business logic.