Junior — Middle
What are the main advantages and disadvantages of using the Active Record pattern?
sobes.tech AI
Answer from AI
The Active Record pattern links an object to a database record, where the object contains methods for reading and writing data.
Advantages:
- Ease of use and understanding.
- Rapid development of CRUD operations.
- Well-suited for small applications with simple logic.
Disadvantages:
- Violation of the single responsibility principle (the object is responsible for both business logic and data access).
- Difficulties with testing due to tight coupling with the database.
- Challenges when working with complex business rules and relationships.
Example in Python using SQLAlchemy:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
def save(self, session):
session.add(self)
session.commit()
# Usage
# user = User(name='Alice')
# user.save(session)