terminal

codeando_simple

terminal

menu

terminal

search_module

guest@codeandosimple: ~/system/search $ grep -r "" .

Press [ENTER] to execute search

Status

Engine: Ready

Database: Online

Index: V2.1.0_LATEST

bash -- cat data-mapper.md
guest@codeandosimple: ~/enterprise/patterns $ cat data-mapper.md

Data Mapper_

// "Every achievement begins with the decision to try"

The Data Mapper is a design pattern that proposes an intermediary component to map data between the database and the application's business objects, without the latter having any knowledge of the database.

This allows for a clear separation between business logic (domain objects) and data access, facilitating the independent maintenance and evolution of both.

# When to use it?

This pattern is ideal in applications where the database structure and the application's domain logic differ significantly, or when it is desired to keep business logic completely decoupled from data access code.

It is especially useful in complex systems, where this separation and abstraction facilitate the management of changes in both the data model and business rules without one directly affecting the other.

# Pros

  • verified

    Separation of Concerns

    Clear distinction between business logic and data access.

  • verified

    Flexibility

    Facilitates changes in the database or business objects with minimal impact.

  • verified

    Reusability and Organization

    Allows for reusing data access logic and better organizing the code.

# Cons

  • warning

    Additional Complexity

    Introduces an extra layer of abstraction, increasing the design complexity.

  • warning

    Learning Curve

    Requires a clear understanding of the pattern and how to implement it properly.

  • warning

    Performance

    The mapping process can introduce additional overhead in some cases.

# Detailed Example in Java

A Data Mapper for Person would be responsible for transferring data between Person instances and the people table without the Person class knowing anything about storage.

PersonMapper.java

public class PersonMapper {
    private Database db; // Assume this is an abstraction for database management

    public PersonMapper(Database db) {
        this.db = db;
    }

    public Person findById(int id) {
        // Performs a database query and constructs a Person instance with the results
    }

    public void save(Person person) {
        // Checks if the person already exists in the database and performs an insertion or update
    }

    // Other methods for updating, deleting, etc.
}

# Conclusions

The Data Mapper pattern facilitates application development and maintenance by separating business logic from data access. Although it can be more complex to implement initially, this separation offers long-term flexibility and scalability.