Mastering Data Transfer Objects and Mapping
In this lesson, you will learn how to decouple your internal business logic from your external presentation layers by using Data Transfer Objects (DTOs) and automated mapping.
The Problem: Leaky Abstractions
Imagine you have a complex User class in your domain layer. It contains sensitive password hashes, internal database IDs, and private state tracking logic. If you pass this User object directly to your API or UI layer, you expose internal details that shouldn't be public. Furthermore, if you change your database schema, your UI might break. This is known as a "leaky abstraction."
The Solution: DTOs
A Data Transfer Object (DTO) is a simple, lightweight object that contains only the data you want to expose to the outside world. It has no behavior—no methods, no logic, just properties.
// Internal Domain Model
public class User {
public int Id { get; set; }
public string Username { get; set; }
public string PasswordHash { get; set; } // Sensitive!
public DateTime LastLogin { get; set; }
}
// Public Data Transfer Object
public class UserDto {
public string Username { get; set; }
}
Mapping the Data
To bridge the gap, you need a way to translate your User into a UserDto. While you could do this manually, as your system grows, you’ll want to use an Auto-mapper. This is a tool that detects property names in both classes and copies values automatically, saving you from writing repetitive conversion code.
By separating these, you gain two major benefits:
- Security: You control exactly what data leaves your system.
- Stability: You can refactor your domain model (e.g., splitting a
Userinto two tables) without forcing your UI team to change their code, as long as your mapping logic produces the sameUserDto.
Essentially, DTOs act as a "buffer" between your system's complex inner workings and the simple requirements of the outside world.
Key Takeaway: Use DTOs to hide your domain’s complexity from the outside world, ensuring that changes to your internal code don't force unnecessary updates in your presentation layer.