SOLID & Design Patterns Interview Question #96
How can the Decorator Pattern be used for logging or validation?
DDD Boundaries, Resilience, Caching & Practical ASP.NET Core Design Mid-Level Intermediate
Quick Interview Answer
A decorator can execute cross-cutting behavior before or after delegating to the wrapped service. For example, a logging decorator can measure execution time, while a validation decorator can reject invalid input before the core service runs.
Detailed Explanation
A decorator can execute cross-cutting behavior before or after delegating to the wrapped service. For example, a logging decorator can measure execution time, while a validation decorator can reject invalid input before the core service runs.
This avoids duplicating the same concern across multiple implementations. Cross-cutting behavior should still be placed at the most appropriate boundary; not every concern needs a decorator.
Code Example
public class ValidatingOrderService : IOrderService
{
private readonly IOrderService _inner;
public Task PlaceAsync(OrderRequest request)
{
if (request.Items.Count == 0)
throw new ValidationException("Items required.");
return _inner.PlaceAsync(request);
}
}