Overview
Entities are domain objects that have a unique identity that persists over time. Unlike value objects, entities are defined by their identity rather than their attributes. In DDD, entities encapsulate business logic and maintain consistency of business rules.Key Characteristics
- Unique Identity: Each entity has a unique identifier (usually
id) - Mutable: Entity attributes can change over time
- Business Logic: Contains domain-specific behavior and validation
- Event Publishing: Can raise domain events for significant state changes
- Lifecycle: Tracks creation and modification times
Entity Structure
Entities in Soft-Bee API follow this pattern:Real Example: User Entity
The User entity from the auth feature demonstrates these principles:src/features/auth/domain/entities/user.py.
Entity Design Principles
1. Identity
Every entity must have a unique identifier:2. Validation
Validate business rules in__post_init__ and dedicated methods:
3. Behavior
Encapsulate business logic in methods:4. Domain Events
Raise events for significant state changes:Creating a New Entity
Step 1: Define the Entity Class
Step 2: Add Business Logic
Step 3: Implement Event Management
Best Practices
Use Value Objects for Complex Attributes
Keep Business Logic in Entities
Always Update Timestamps
Validate on Construction
Common Patterns
Soft Delete
Status Transitions
Collection Management
Related Documentation
- Value Objects - Immutable domain objects
- Domain Events - Event-driven architecture
- Domain Exceptions - Error handling