The user wants a "domain policy engine" built using specific software design concepts:
- Specification Pattern: This is a pattern where business rules can be represented as objects, allowing them to be combined and reused. A
Specification usually has an isSatisfiedBy(candidate) method.
- Composable Rules: This implies the specifications can be chained together using logical operators (AND, OR, NOT).
- Caching: The engine should cache the results of expensive rule evaluations to improve performance.
I need to structure the solution in a way that demonstrates these concepts clearly. I'll choose a concrete, easy-to-understand domain to make the code relatable. An E-commerce Order Approval System is a classic and effective choice for this.
High-Level Design:
- Domain:
Order entity (containing total, items, customer info).
- Core Interface:
ISpecification with IsSatisfiedBy(T candidate).
- Composable Logic: Base class or extension methods for
And, Or, Not.
- Caching Layer: A wrapper or proxy around the specification execution that checks a cache (like
IMemoryCache in .NET or a simple dictionary map) before executing the actual logic.
- Engine: A
PolicyEngine class that evaluates a set of rules against a context.
Step-by-Step Implementation Plan:
- Define the Domain: Simple
Order class.
- Define the Specification Interface:
ISpecification<T>.
- Implement Composite Specifications: Classes like
AndSpecification, OrSpecification, NotSpecification.
- Implement Concrete Rules: Examples:
HighValueOrderSpec, LoyalCustomerSpec.
- Implement Caching:
- Challenge: How to cache specific evaluations?
- Approach: Create a
CachedSpecification decorator. It takes the inner specification and a cache key strategy. When IsSatisfiedBy is called, it generates a key, checks the cache, and returns if found. If not, it calls the inner spec, caches the result, and returns.
- The Engine: A simple runner that combines rules and executes them.
Refining the Caching Strategy:
Cache invalidation is hard. For a stateless policy engine, the cache key usually needs to depend on the type of the specification and the identity or hash of the candidate object.
- Simple approach:
GetType().Name + "_" + candidate.Id.
Language Choice: C# is excellent for this because of LINQ expressions, strong typing, and standard interfaces like IQueryable often associated with the Specification pattern, though for this specific prompt, standard object-oriented implementation is clearer than full Expression tree parsing. I will stick to a clean C# implementation.
Drafting the Code Structure (Mental or scratchpad):
ISpecification
bool IsSatisfiedBy(T entity)
ISpecification And(ISpecification other)
Order class
Customer class
SimpleSpec : ISpecification (Concrete)
CachedSpec : ISpecification (Decorator)
Adding Complexity/Realism:
To make it "engineering" level, I shouldn't just do return x > 5. I should demonstrate how to handle a policy that consists of multiple rules.
Maybe the engine returns a PolicyResult containing why it failed, not just a boolean?
- Prompt Constraint: The prompt asks for the engine leveraging the pattern, not necessarily a full validator with error messages, but adding "Reasons" makes it much more useful. Let's stick to boolean first to keep the pattern clear, maybe add a
Reason property if easy, otherwise stick to the requested core: Specification + Composition + Caching.
Revised Plan for Caching:
Since specifications are stateless (usually), caching the result of a logical operation on a specific object state is valuable if the object hasn't changed but the check is run multiple times, OR if the check is expensive (e.g., database call).
I will implement an interface ICacheService to abstract the caching mechanism.
Let's write the code (Mental Draft):
public interface ISpecification {
bool IsSatisfiedBy(T candidate);
}
public class AndSpec ... { ... }
public class OrSpec ... { ... }
For caching, a Decorator pattern is best.
public class CachedSpecification : ISpecification {
ISpecification _inner;
ICache _cache;
public bool IsSatisfiedBy(T candidate) {
var key = GenerateKey(candidate);
return _cache.GetOrCreate(key, () => _inner.IsSatisfiedBy(candidate));
}
}
Putting it together:
- Core Interfaces: Define
ISpecification.
- Composable Base: Implement logical operators (
And, Or, Not) as reusable classes.
- Domain & Concrete Specs: Create
Order and rules like PremiumMemberSpec, InventoryCheckSpec.
- Caching Decorator: Implement the caching logic.
- Engine: The
PolicyEngine class that accepts a context and a root specification.
Self-Correction during drafting:
The user asked for a "Policy Engine". Just having specs isn't an engine. The engine should probably handle the execution lifecycle.
Also, the caching key generation needs to be robust enough to handle different objects. typeof(T).GUID + candidate.GetHashCode() (if overridden) is a safe bet for a demo.
Let's produce the output in C# as it's the most idiomatic language for the Specification Pattern due to its static typing and LINQ capabilities, though Python/Java are also fine. I will stick with C# for clarity and robustness.
Final Polish:
Ensure the code is production-ready style:
- Dependency Injection ready.
- Thread-safe considerations (mentioned).
- Clear separation of concerns.
Let's execute.
Here is a complete engineering implementation of a Domain Policy Engine in C#. This solution utilizes the Specification Pattern for business rules, supports Logical Composition (AND/OR/NOT), and implements a Caching Decorator to optimize performance for expensive evaluations.
Architecture Overview
ISpecification<T>: The core interface defining the contract for a business rule.
- Composite Specifications: Classes (
And, Or, Not) that allow chaining rules together.
- Domain Model: A sample context (e.g., an
Order in an e-commerce system).
- Caching Layer: A Decorator pattern that wraps specifications to cache the boolean result of the evaluation.
Implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DomainPolicyEngine
{
// =================================================================
// 1. Core Abstractions
// =================================================================
/// <summary>
/// The Specification Pattern interface.
/// </summary>
/// <typeparam name="T">The entity type to evaluate.</typeparam>
public interface ISpecification<T>
{
bool IsSatisfiedBy(T candidate);
// Helper to allow async/await support if external calls are needed (optional for this demo)
// Task<bool> IsSatisfiedByAsync(T candidate);
}
/// <summary>
/// Interface for a cache provider abstraction.
/// </summary>
public interface ISpecificationCache
{
bool TryGetResult(string cacheKey, out bool result);
void SetResult(string cacheKey, bool result);
}
// =================================================================
// 2. Composable Base Logic
// =================================================================
/// <summary>
/// Base class providing composition operators (And, Or, Not).
/// </summary>
public abstract class CompositeSpecification<T> : ISpecification<T>
{
public abstract bool IsSatisfiedBy(T candidate);
public ISpecification<T> And(ISpecification<T> other)
{
return new AndSpecification<T>(this, other);
}
public ISpecification<T> Or(ISpecification<T> other)
{
return new OrSpecification<T>(this, other);
}
public ISpecification<T> Not()
{
return new NotSpecification<T>(this);
}
}
// Concrete Composable Implementations
public class AndSpecification<T> : CompositeSpecification<T>
{
private readonly ISpecification<T> _left;
private readonly ISpecification<T> _right;
public AndSpecification(ISpecification<T> left, ISpecification<T> right)
{
_left = left ?? throw new ArgumentNullException(nameof(left));
_right = right ?? throw new ArgumentNullException(nameof(right));
}
public override bool IsSatisfiedBy(T candidate)
{
// Short-circuit evaluation logic
return _left.IsSatisfiedBy(candidate) && _right.IsSatisfiedBy(candidate);
}
}
public class OrSpecification<T> : CompositeSpecification<T>
{
private readonly ISpecification<T> _left;
private readonly ISpecification<T> _right;
public OrSpecification(ISpecification<T> left, ISpecification<T> right)
{
_left = left;
_right = right;
}
public override bool IsSatisfiedBy(T candidate)
{
// Short-circuit evaluation logic
return _left.IsSatisfiedBy(candidate) || _right.IsSatisfiedBy(candidate);
}
}
public class NotSpecification<T> : CompositeSpecification<T>
{
private readonly ISpecification<T> _spec;
public NotSpecification(ISpecification<T> spec)
{
_spec = spec;
}
public override bool IsSatisfiedBy(T candidate)
{
return !_spec.IsSatisfiedBy(candidate);
}
}
// =================================================================
// 3. Caching Decorator
// =================================================================
/// <summary>
/// Wraps a specification and caches the result based on a unique key derived from the entity.
/// </summary>
public class CachedSpecification<T> : ISpecification<T>
{
private readonly ISpecification<T> _innerSpecification;
private readonly ISpecificationCache _cache;
private readonly Func<T, string> _keyGenerator;
public CachedSpecification(
ISpecification<T> innerSpecification,
ISpecificationCache cache,
Func<T, string> keyGenerator)
{
_innerSpecification = innerSpecification;
_cache = cache;
_keyGenerator = keyGenerator;
}
public bool IsSatisfiedBy(T candidate)
{
string cacheKey = $"{typeof(T).Name}_{_innerSpecification.GetType().Name}_{_keyGenerator(candidate)}";
if (_cache.TryGetResult(cacheKey, out bool cachedResult))
{
Console.WriteLine($"[Cache Hit] Key: {cacheKey}");
return cachedResult;
}
Console.WriteLine($"[Cache Miss] Evaluating: {cacheKey}");
bool result = _innerSpecification.IsSatisfiedBy(candidate);
_cache.SetResult(cacheKey, result);
return result;
}
}
// =================================================================
// 4. Infrastructure Implementation (Simple Memory Cache)
// =================================================================
public class InMemorySpecificationCache : ISpecificationCache
{
private static readonly Dictionary<string, bool> _cacheStore = new Dictionary<string, bool>();
// In a real scenario, use MemoryCache or Redis with expiration policies
public bool TryGetResult(string cacheKey, out bool result)
{
return _cacheStore.TryGetValue(cacheKey, out result);
}
public void SetResult(string cacheKey, bool result)
{
_cacheStore[cacheKey] = result;
}
}
// =================================================================
// 5. Domain Model & Concrete Rules
// =================================================================
public class Order
{
public int Id { get; set; }
public decimal TotalAmount { get; set; }
public string CustomerSegment { get; set; } // "VIP", "Regular"
public bool IsHighRisk { get; set; }
}
// Rule 1: Is the order expensive?
public class HighValueOrderSpecification : CompositeSpecification<Order>
{
private readonly decimal _threshold;
public HighValueOrderSpecification(decimal threshold)
{
_threshold = threshold;
}
public override bool IsSatisfiedBy(Order candidate)
{
// Simulate expensive calculation
System.Threading.Thread.Sleep(50);
return candidate.TotalAmount > _threshold;
}
}
// Rule 2: Is the user VIP?
public class VipCustomerSpecification : CompositeSpecification<Order>
{
public override bool IsSatisfiedBy(Order candidate)
{
return candidate.CustomerSegment == "VIP";
}
}
// Rule 3: Fraud check
public class FraudRiskSpecification : CompositeSpecification<Order>
{
public override bool IsSatisfiedBy(Order candidate)
{
// Simulate external API call
System.Threading.Thread.Sleep(100);
return candidate.IsHighRisk;
}
}
// =================================================================
// 6. The Policy Engine
// =================================================================
public class PolicyEngine
{
private readonly ISpecificationCache _cache;
public PolicyEngine(ISpecificationCache cache)
{
_cache = cache;
}
// Helper to wrap rules in caching
private ISpecification<Order> CacheRule(ISpecification<Order> spec)
{
// Generate key based on Order ID
return new CachedSpecification<Order>(spec, _cache, (order) => order.Id.ToString());
}
public void EvaluateOrder(Order order)
{
Console.WriteLine($"\n--- Evaluating Order {order.Id} ---");
// Define Composable Policy:
// Policy: (HighValue AND VIP) OR (NOT FraudRisk)
var isHighValue = new HighValueOrderSpecification(5000);
var isVip = new VipCustomerSpecification();
var isFraud = new FraudRiskSpecification();
// Compose them
var policy = CacheRule(isHighValue)
.And(CacheRule(isVip))
.Or(CacheRule(isFraud).Not());
// Note: Caching composite trees requires careful keying strategies.
// Here we wrap specific expensive leaves in caching.
bool isApproved = policy.IsSatisfiedBy(order);
Console.WriteLine($"Order {order.Id} Approved: {isApproved}");
}
}
// =================================================================
// 7. Execution / Testing
// =================================================================
class Program
{
static void Main(string[] args)
{
var cache = new InMemorySpecificationCache();
var engine = new PolicyEngine(cache);
var order1 = new Order { Id = 101, TotalAmount = 6000, CustomerSegment = "VIP", IsHighRisk = false };
var order2 = new Order { Id = 102, TotalAmount = 100, CustomerSegment = "Regular", IsHighRisk = false };
// Duplicate of order 1 to demonstrate cache
var order3 = new Order { Id = 101, TotalAmount = 6000, CustomerSegment = "VIP", IsHighRisk = false };
// First Run (Cache Misses)
engine.EvaluateOrder(order1);
// Second Run (Different ID, mostly misses)
engine.EvaluateOrder(order2);
// Third Run (Same ID as Order 1)
// You will see Cache Hits for the HighValue and Fraud checks if keys match
engine.EvaluateOrder(order3);
}
}
}
Key Engineering Decisions
- Composition over Inheritance: The
CompositeSpecification base class allows infinite chaining of rules (And, Or, Not) without creating rigid class hierarchies.
- Caching Strategy:
- We use the Decorator Pattern via
CachedSpecification.
- This allows us to selectively cache specific expensive rules (like a Fraud API call) rather than caching the entire boolean expression tree blindly.
- The key generation strategy (
Func<T, string>) ensures we don't return false positives for different entities with similar properties.
- Short-Circuiting: The
AndSpecification and OrSpecification use standard && and || operators. This ensures that if the first rule fails (or passes in OR logic), the second (potentially expensive) rule is never executed, saving resources before the cache is even checked.