tezvyn:

Data Mapper Pattern: Decoupling Your Domain from Your DB

AI-drafted, machine-checkedSource: Wikipedia: Data mapper patternadvanced

A Data Mapper is a dedicated layer that moves data between in-memory objects and a database. This decouples your business logic from persistence, keeping domain objects clean and unaware of the database schema. It's the opposite of the Active Record pattern.

WHY IT EXISTS Applications need to store the state of their business objects, like a User or an Order, in a database. Tightly coupling this persistence logic to the business objects themselves makes the system rigid, hard to test, and difficult to change. The Data Mapper pattern was created to solve this by introducing a clean layer of separation.

THE MENTAL MODEL Imagine a professional translator who is fluent in two languages: your application's domain objects and your database's table structure. Your business logic speaks only to the domain objects. When it's time to save or load data, you hand an object to the translator (the Mapper), which handles all the details of converting it to and from database rows. The domain object itself doesn't know or care that a database exists.

HOW IT WORKS A Data Mapper is a class that contains the logic for transferring data between a specific domain object and the database. For a User object, you would have a UserMapper. This mapper would have methods like Create, Read, Update, and Delete (e.g., find(id), insert(user)). When you call userMapper.insert(user), the mapper takes the user object, extracts its data, constructs the appropriate SQL query, executes it, and might update the object with a database-generated ID. The User object itself contains no SQL or persistence logic.

WHEN TO USE IT Use the Data Mapper pattern in complex applications where your domain model is rich with business logic and you want to keep it pure and independent of storage concerns. It's ideal when the database schema and your object model diverge significantly, as the mapper can handle complex transformations between the two.

WHEN NOT TO USE IT For simple CRUD applications where the domain objects are little more than data containers that map directly to database tables, the Data Mapper can be overkill. In these cases, a simpler pattern like Active Record might be more efficient to implement.

ONE CANONICAL EXAMPLE Consider a User object in your application. Instead of having a user.save() method, you would have a separate UserMapper. To save a new user, your code would look like this: newUser = new User('Alice'); userMapper = new UserMapper(dbConnection); userMapper.insert(newUser);. Notice how the User class is completely decoupled from the UserMapper and the database.

Read the original → en.wikipedia.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.