You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
21 Hrs
12 Min
20 Seg

Modelo de Dominio

14/24
Resources

What is a domain model?

The domain model is an advanced way of organizing the domain in object-oriented programming (OOP). Contrary to anemic models, where objects do not take full advantage of OOP capabilities by having limited data or behaviors, a domain model integrates both behaviors and data. This allows objects to not only store information, but to perform meaningful operations and handle their own methods, which greatly enriches the interaction and functionality of the system.

How is a domain model different from a database model?

Confusion is often created between domain models and database models. A database model, generally referred to as a schema, is structured specifically for data management in a persistence environment, such as a SQL database with tools like the Entity Framework. Here it is common to find classes that denote characteristics of database fields such as primary keys, foreign keys and data validations. In contrast, in a domain model, classes are not necessarily tied to the database structure but are focused on representing business logic and behavior. This implies that OOP principles such as inheritance and polymorphism are leveraged to create objects that interact more richly within the application.

What components can a domain model include?

When developing a domain model, several elements are considered that enhance its functionality and maintainability. These include:

  • Entities: these are the core elements that represent real-world objects and have a unique identity in the context of the domain.

  • Value objects: Unlike entities, these objects have no identity of their own and their main function is to group related data. A common example is a route that encompasses an origin and a destination.

  • Inheritance and relationships: Inheritance allows extending the functionalities of a base class, while relationships connect different entities and objects to form a more robust network.

  • Design patterns: These are used to manage complex structures and promote code reuse.

These components create a cohesive system where the entities of the domain model are able to perform shared operations without overloading the logic of the services.

Practical example: Domain model applied

When applying a domain model, the classic example is that of a Flight entity that not only holds data, such as flight details, but also handles meaningful behaviors. For example:

public class Flight { public public int NumeroAsientosDisponibles { get; private set; } private List<Booking> Reservations;
 public void AgregarReservacion(Booking booking) { if (IsAvailable(booking.Pasajeros)) { Reservas.Add(booking); NumeroAsientosDisponibles -= booking.Pasajeros; } } }
 public bool IsAvailable(int pasajeros) { return NumeroAsientosDisponibles >= pasajeros; } }}

Here, Flight handles its own bookings and validates seat availability internally. This not only simplifies the purpose of the object, but gives it a more meaningful scope compared to a purely transaction-centric approach.

How are services impacted by the domain model?

Adopting a domain model positively impacts the services layer of the application. Services, which previously might have redundant logic in the work of validations and behaviors, now delegate these responsibilities to the relevant domain objects. Thus, operations such as validating a route or checking the availability of a flight are now handled directly within domain objects, leaving services to focus on coordinating rather than validating.

On the way to further optimizing the code, this approach allows objects to be reused in different contexts without the need to duplicate logic in different parts of the application. This principle not only improves maintainability, but also speeds up software development and extension.

Contributions 8

Questions 6

Sort by:

Want to see more contributions, questions and answers from the community?

Modelo de dominio

Es una representación en objetos del dominio, que incluye comportamiento y datos de manera simultánea y no anémicos (con datos pero sin comportamiento y viceversa).

Modelo de dominio ≠ Modelo de base de datos

¿Qué puede incluir un modelo de dominio?

  • Entidades.
  • Objetos de valor.
  • Herencia.
  • Relaciones.
  • Patrones de diseño.

El término Objeto de Valor también es muy usado con el término de ValueObject en recursos que están en inglés

Estoy recién haciendo éste curso y noté une ligero cambio en la interfaz de visualización de los temas de clase y los comentarios. Hasta la semana pasada podía acceder a los "Recursos" pero desde ésta semana ya no veo por dónfe puedo ingresar a ellos. Agradezco si me pueden dar otientación.
## ¿Cómo saber cuándo usar una Entidad o un Objeto de valor? ### Usa una **Entidad** cuando: * Necesitas **seguir su identidad en el tiempo** (ej.: usuario, pedido, tarjeta). * Va a vivir en la base de datos con un **ID propio**. * Tiene **ciclo de vida** y puede mutar o tener historial. ### Usa un **Objeto de Valor** cuando: * Es un **atributo compuesto** que necesita validación/lógica. * No tiene identidad ni ciclo de vida. * **Importa el qué es**, no el quién es. * Quieres evitar usar `String`, `double` o `int` genéricos que pueden prestarse a errores.
Mi cabeza acaba de hacer boom... respecto a cómo venía manejando las cosas, donde los objetos son solo contenedores de datos y la lógica vive completamente en servicios. En resumen: Sí, es una buena práctica tener cierta lógica de negocio dentro de los modelos, siempre y cuando esté alineada con los principios de diseño orientado a objetos (OOP), particularmente con el principio de encapsulamiento y el modelo rico (Rich Domain Model). ¿Cuándo es recomendable incluir lógica de negocio en un modelo? * La lógica del dominio está dentro del propio modelo. * Mejora la cohesión, el encapsulamiento y la inmutabilidad. * Reduce la dispersión de reglas de negocio y errores por mal uso. Problemas al manejar objetos solo como contenedores de datos: Menor cohesión, mayor riesgo de errores de dominio. Tener en cuenta al decidir dónde poner la lógica: * Validaciones del estado del objeto: Modelo (entidad/objeto) * Cálculos derivados del propio objeto: Modelo * Interacciones con otros objetos: Servicio de dominio * Acciones que dependen de infraestructura (API, DB, correo): Servicio / repositorio Palabras más, palabras menos... * Pon lógica de negocio relevante en el modelo si depende solo del propio objeto. * Usa servicios para orquestar, pero no sobrecargues con lógica interna.