0Pricing
Clean Architecture & Design Patterns in Practice · Lección

Data Mappers y DTO

Aprenda a mapear datos entre entidades internas y estructuras de datos externas (DTO) para interactuar con bases de datos o API.

Data Mappers y DTO es una lección gratuita de Clean Architecture & Design Patterns in Practice en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Clean Architecture & Design Patterns in Practice, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Mapping Data: Why We Need It

In Clean Architecture, your core business logic (Entities and Use Cases) should be independent of external details like databases or web frameworks.

But how do your internal data structures communicate with the outside world? This is where Data Mappers and Data Transfer Objects (DTOs) come in.

Entities vs. External Data

Your Entities contain crucial business rules and are designed for your domain logic. They often have methods and complex relationships.

Exposing these entities directly to external layers (like a database or an API) can lead to:

  • Tight Coupling: Changes in your database or API might force changes in your core entities.
  • Security Risks: You might expose sensitive internal data.
  • Data Shape Mismatch: External systems often need data in a different format than your internal domain model.

Introducing Data Transfer Objects (DTOs)

A Data Transfer Object (DTO) is a simple object used to transfer data between different layers or processes. Think of it as a plain data container.

Key characteristics of DTOs:

  • They only hold data, typically public fields or simple getters/setters.
  • They contain no business logic.
  • They are designed for specific external communication needs (e.g., API request/response, database record).

DTOs in Action: An Example

Let's imagine a Product entity in our core domain and a ProductDto for communicating with an external API.

Notice how the DTO fields might be named differently or represent a subset of the entity's data.

class Product { // Internal Entity
  private String id;
  private String name;
  private double price;
  // ... business methods
}

class ProductDto { // External DTO
  public String productId;
  public String productName;
  public double productPrice;
  // No business logic here
}

The Role of Data Mappers

A Data Mapper is an object responsible for converting data between your internal Entities and external DTOs (and vice-versa).

It acts as a translator, ensuring your core domain remains clean and isolated. Mappers protect your entities from changes in external data formats.

Implementing a Simple Data Mapper

A data mapper typically has methods to convert from an entity to a DTO, and from a DTO back to an entity.

This allows controlled data flow and transformation.

class ProductMapper {
  public ProductDto toDto(Product product) {
    if (product == null) return null;
    return new ProductDto(
      product.getId(),
      product.getName(),
      product.getPrice()
    );
  }

  public Product toEntity(ProductDto dto) {
    if (dto == null) return null;
    return new Product(
      dto.productId,
      dto.productName,
      dto.productPrice
    );
  }
}

Using the Data Mapper

Here's how you'd use a ProductMapper to convert between your internal Product entity and its external ProductDto representation.

Try running this example!

public class Main {
  // Product Entity (simplified for demo)
  static class Product {
    private String id;
    private String name;
    private double price;

    public Product(String id, String name, double price) {
      this.id = id;
      this.name = name;
      this.price = price;
    }
    public String getId() { return id; }
    public String getName() { return name; }
    public double getPrice() { return price; }
  }

  // Product DTO (simplified for demo)
  static class ProductDto {
    public String productId;
    public String productName;
    public double productPrice;

    public ProductDto(String productId, String productName, double productPrice) {
      this.productId = productId;
      this.productName = productName;
      this.productPrice = productPrice;
    }
  }

  // Data Mapper
  static class ProductMapper {
    public ProductDto toDto(Product product) {
      if (product == null) return null;
      return new ProductDto(
        product.getId(),
        product.getName(),
        product.getPrice()
      );
    }

    public Product toEntity(ProductDto dto) {
      if (dto == null) return null;
      return new Product(
        dto.productId,
        dto.productName,
        dto.productPrice
      );
    }
  }

  public static void main(String[] args) {
    Product originalProduct = new Product("A101", "Keyboard", 75.00);
    ProductMapper mapper = new ProductMapper();

    ProductDto productDto = mapper.toDto(originalProduct);
    System.out.println("DTO Name: " + productDto.productName);

    Product convertedProduct = mapper.toEntity(productDto);
    System.out.println("Entity Name: " + convertedProduct.getName());
  }
}

DTOs for Different Contexts

You don't just need one DTO per entity! Different external interactions might require different data shapes:

  • ProductRequestDto: For creating or updating a product via an API.
  • ProductResponseDto: For sending product details back from an API.
  • ProductSummaryDto: For a list view, only showing ID, name, and a short description.

Each DTO serves a specific purpose, keeping data transfer lean and relevant.

Benefits of Mappers and DTOs

Using Data Mappers and DTOs offers significant advantages in Clean Architecture:

  • Decoupling: Protects your core domain from external changes.
  • Flexibility: Easily adapt to new external data formats without altering entities.
  • Security: Control exactly what data is exposed or accepted.
  • Clear Contracts: DTOs define explicit contracts for external communication.
  • Testability: Mappers are simple to unit test in isolation.

Test Your Knowledge

Which of the following best describes the primary purpose of a Data Transfer Object (DTO) in Clean Architecture?

Recap: Mappers & DTOs

You've learned how Data Mappers and Data Transfer Objects (DTOs) are vital for maintaining the independence of your core domain in Clean Architecture.

  • DTOs are plain data structures for external communication.
  • Data Mappers translate between your internal Entities and these external DTOs.

This pattern ensures your business logic remains pure, flexible, and decoupled from external concerns.

Preguntas frecuentes

¿La lección «Data Mappers y DTO» es gratis?

Sí — el texto completo de «Data Mappers y DTO» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Clean Architecture & Design Patterns in Practice, actualiza a CoddyKit PRO. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.

¿Qué aprenderé en «Data Mappers y DTO»?

Aprenda a mapear datos entre entidades internas y estructuras de datos externas (DTO) para interactuar con bases de datos o API. Practicas Clean Architecture & Design Patterns in Practice con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Clean Architecture & Design Patterns in Practice?

No se requiere experiencia previa. Clean Architecture & Design Patterns in Practice en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Data Mappers y DTO»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Clean Architecture & Design Patterns in Practice?

Sí. Cada lección de Clean Architecture & Design Patterns in Practice incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. El patrón Repository en la Arquitectura Limpia
  2. Interfaces Gateway para sistemas externos
  3. Data Mappers y DTO
  4. Capas anticorrupción para API de terceros
← Volver a Clean Architecture & Design Patterns in Practice