Uncoupling Configuration Files

Tight coupling is a known source for inflexible and hard to test code. In this post I want to talk about a rather unexpected source of tight coupling - configuration files. Configuration files are external dependencies. As other external dependencies, its infrastructure may change in the future, and it should be easily mocked for unit testing. Modern software frameworks provide means for easy access to the values stored in configuration files. In the .NET framework configuration files can be accessed using the ConfigurationManager:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="Foo" value="1"/>
    <add key="Bar" value="2"/>
  </appSettings>
</configuration>
int foo = int.Parse(ConfigurationManager.AppSetttings[“Foo”]);
int bar = int.Parse(ConfigurationManager.AppSettings[“Bar”]);

ConfigurationManager makes it trivial to access data in the config file, however in most cases it also introduces various code smells that make the code tight coupled and hard to test. In the next sections I’ll introduce a simple class and will use it to demonstrate the code smells and violations of principles of clean object oriented design. The code will be gradually refactored to a better and cleaner solution.

[Read More]