We have a quite common object in our application. In this case, we’ll call it a Ball. Balls work fine, but in some configurations they act differently. It is currently set up like this:
class Ball
{
private static readonly bool BallsCanExplode;
static Ball()
{
bool.TryParse(ConfigurationManager.AppSettings["ballsCanExplode"],
out BallsCanExplode);
}
public Ball(){}
}
This works completely fine in practice. If the configuration is that balls can explode, they explode, and if not, not. The problem is that it is completely non-testable. I haven’t been able to figure out a good way to keep it testable, and still easy to instantiate.
The simplest solution is to just decouple the ball and the configuration:
class Ball
{
private readonly bool CanExplode;
public Ball(bool canExplode);
}
The problem with this is that what was once an isolated dependency in the Ball class has now spread to every single class that makes a Ball. If this gets dependency injected in, then the knowledge of exploding balls has to get injected everywhere.
The same problem exists with a BallFactory. While every class could just go new Ball(), it now has to know about a BallFactory that has to be injected everywhere. The other option is to use the Service Locator which is already baked in to the application:
class Ball
{
private readonly bool CanExplode;
public Ball()
{
CanExplode = ServiceLocator.Get<IConfiguration>().Get("ballsCanExplode");
}
}
This still keeps the configuration dependency in the ball, but allows a test configuration to be injected in. Balls are used so much though, that it seems like overkill to locate the service on every new Ball() call.
What would be the best way to keep this testable, as well as easy to instantiate?
Note: There is both a dependency injection framework and service locator in the application, which are both used frequently.
Classes that instantiate balls should receive a
BallFactoryas a dependency. TheBallFactorycan be configured accordingly as application startup whether or not to produce exploding balls or non-exploding balls.Don’t have the
BallFactoryread the application configuration file to determine which types of balls to produce. That should be injected into theBallFactory.Service locators are an anti-pattern. Don’t use them.