We use domain objects to encapsulate business logic. Sometimes, we need to change the behavior of an entity due to new system requirements. A common approach is to modify the method or property by adding an if statement that checks a feature flag:
public class Entity : IEntity
{
public void SomeMethod()
{
if (Feature.NewRequirement())
{
DoTheNewStuff();
}
else
{
DoTheOldStuff();
}
}
}
The feature flag determines when the new behavior should be enabled and allows us to turn it off if necessary. Typically, after the feature has been running in production for a few weeks or months, we remove the flag and keep only the new implementation.
Problems With This Approach
- Feature Flag as a Static Dependency – The Feature class is static and depends on a cache holding the feature flag configuration. This makes unit testing difficult since shared state in tests can cause flakiness and prevent parallel execution.
- Injecting the Feature Flag? – We could pass the feature flag as a constructor argument to Entity or as a method parameter, but we prefer to keep domain objects as pure as possible, without dependencies on infrastructure. Most of the time, entities are either created by an aggregate or fetched from a database via an ORM.
How can we make our domain entities behave differently based on feature flags while minimizing dependencies and avoiding static calls inside the entity?