The intersection of technology and leadership

Treat your App.config like a global variable

I remember looking at a few codebases in C# and it surprised me how many people encapsulate some of their system well, yet treat their application configuration as a different thing. Many times I’ve seen code that looks like: ConfigurationSettings.AppSettings["DatabaseConnectionString"]; alongside the thing that is using it. In fact, I often see this code repeated in various parts of the system wherever anyone needs to draw on application configuration.

Global variables are bad
Most good programmers seem to realise that most global variables are bad, yet this is exactly what I think accessing the application configuration is like. If you want to change the way your configuration is loaded (i.e. programmatically or from a database) think of how many places you now need to change it, let alone how it effects the order in which you instantiate objects.

My advice: Separate the use of configuration from where it declared
I try to follow the pattern isolating the configuration into a single class depending on the access method, such as:

  • DatabaseBackedConfiguration
  • FileBackedConfiguration
  • DefaultInMemoryBackedConfiguration

Each of these classes them implement several roles depending on what configuration they might provide such as:

  • HibernateConfiguration
  • ApplicationConfiguration
  • ArchivingConfiguration

Having smaller roles makes it clearer what sort of configuration is really needed for a particular consumer, and it allows me to change the decision about how that configuration is now provided to it. It enables me to do things like specify different environment configurations and do so in the method that I prefer.

3 Comments

  1. felix

    I really like that pattern. Configuration is an object (not a properties file or whatever). In a previous project this allowed us to bring up two different instances of the application inside the same vm and gave us the abilitiy to integration test server to server communication.

  2. Vikram Nayak

    Nice post.

  3. Josh Ribakoff

    Even better then passing around a config option is to parametrize the method

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 patkua@work

Theme by Anders NorenUp ↑