Thursday, 16 February 2012

Abstracting the Configuration Manager

Whilst browsing a few blogs earlier this week I came across this post which talks about creating a wrapper around the ASP.NET ConfigurationManager.  For those who don't know the ConfigurationManager class makes pulling settings out of the Web.Config (or App.Config) very straightforward.

I found this post interesting for two reasons -
  1. It encapsulates (at least for me) the difference between a fresh out of University programmer and a more experienced programmer. 
  2. I don't think it goes far enough - it can be extended further by introducing an abstraction with the added benefit of making it much easier to unit test.
As an inexperienced programmer just starting out it is all to easy (and I have done it myself) to start littering code with lines like this -

string emailTo = ConfigurationManager.AppSettings["emailTo"];

There are a few things wrong with doing this but the most important is what happens if for some reason it is decided to remove the application settings from the config file and use a database table instead? The only real option open to you in this case is an error prone find and replace routine - not ideal!

The answer is to not directly reference the ConfigurationManager but as the article suggests create a wrapper around it - so you would create an AppConfig class with methods for getting settings (see the referenced post for implementation details).

If this class is used correctly and consistently throughout the application then you now have only one class in your application where ConfigurationManager is referenced so now if a change is required to store in a database you only have to update the code in a single class.

This is where the post finishes and a year or so ago I probably would have as well but there is still a problem with it - what if after changing the code to read from a database your (indecisive) boss decides he wants to change back? You can start to see why this is not a particularly good way to go about things - it breaks the Open/Closed principal - once a class is built it should not be modified (except in the case of bugs which is a source of debate).

There is a much more elegant way to do this - simply create an abstraction. Couple this with Dependancy Injection and it becomes a very flexible solution to the problem. The way I would do it is to create the following interface -

public interface IConfigurationManager
{
   public string GetSetting(string key, string defaultValue);
   //Other methods for different types
}

Then you can refactor the AppConfig class to implement the interface - you can then refactor your calling code to use the interface rather than a concrete class and use Dependency Injection to supply an implementation at runtime.

Now if you need to change to a database storage system all you need to do is create a new class that implements the IConfigurationManager interface such as -

public class DatabaseSettings : IConfigurationManager
{
    public string GetSetting(string key, string defaultValue)
    {
        //pull setting from DB
    }
}

Now the only place where you will need to alter any code is the code that wires up the Dependancy Injection configurations (which could be none at all if you have configured through XML/config file) - now the Open/Closed principal is not being violated and swapping back to the old method is simply a matter of changing the dependency injection configuration! A far better way to do things I'm sure you will agree.

Of course there is still more than can be done with this although I think that is good enough for now but for a more comprehensive example see this post

I'm Back

This blogging thing is trickier than I thought - having the time to actually sit down and right a blog post is one thing but actually having something to say is another entirely! 

After several months of silence I am going to have another try - this time I aiming to do at least 1 blog post every week - so lets see how it goes.  

Sunday, 18 September 2011

Good Programming Practice

This week I have spent some time playing with jQuery components and as a programmer I am always interested in understanding the code rather than just plugging it in and leaving it that. One thing that struck me looking through the source is the amount of code that looks like this
  if (condition) 
      DoSomething();
The key point about this code is the lack of curly braces around the if/else statements - this is a practice I have always tried to avoid and don't particularly like. The truth of course is that with or without braces the code will do exactly the same thing and the issue is more to do with semantics and readability than it is to do with the code itself.

I mentioned this on Twitter and got some interesting responses back from other developers - the main one being that this is probably a language specific question as many languages/frameworks simply won't allow this sort of syntax in the first place.

I have stolen borrowed C# code from the web on many occasions and have very rarly seen this type of code yet in JavaScript it seems to be the norm. Why this is the case I am not really sure, of course file size is an issue in JavaScript which is not so relevant in C# due to its compiled nature but if you are following best practices then you are already minifying your scripts before going live anyway (you are aren't you?) so an extra few lines in your uncompressed files will make little different after compression.

The other thing that people mentioned on Twitter is that the code above would not be acceptable but if it all sat on one line then it would probably would be alright, like this -
  if (condition) DoSomething();
The difference it minimal but from a readability point of view I can see justification for it. It is much clearer what is intended - the problem with the first case is it may be possible for a future developer to come along and do the following
  if (condition) 
      DoSomething();
      DoNextThing();
Which would obviously not do what was expected - this is just a hypothetical case and probably wouldn't really happen in reality but it opens up the possibility that it could. The simple answer is to program defensively and, as most people on Twitter seemed to agree, add the braces in.

What is your opinion? Is there ever a valid reason not to add the braces? What happens in other languages?

Saturday, 13 August 2011

ELMAH

In my last post about ASP.NET MVC I mentioned ELMAH (Error Logging Modules and Handlers) and thought I would expand on what it is and what it does. In essence it is a way of logging unhandled errors in your code - one of the key features which I like is it is able to be used on a running app without the need to recompile and deploy.

As a good programmer I am sure that you always try to catch errors and recover gracefully from them - you also probably log those errors to a database or file. Unfortunately however hard you try a user will find a way to break your well crafted code - of course if you have done things correctly they will see a nice custom error page, rather than the yellow screen of death.

The problem with this is that because these errors are unhandled and not logged finding out exactly what caused the error is not exactly easy, in my experience relying on users to give you any useful information is not a great strategy, in a perfect world what you really want is to be able to see the actual yellow screen of death with the full error and stack trace. This is what ELMAH gives you, with just a few lines in the Web.config it can log the error details to a database (or any other of its supported storage methods) - the error log can then be opened in a browser and in most cases the original error screen can be viewed.

The advantages for tracking individual errors are obviously massive however for every error that is reported there must be a whole bunch which are not reported - ELMAH lets you track these as well, in fact this is one of the main reasons the guys at Stackoverflow use it.

One small issue I would note is that the original code only works with CustomErrors set to false, which for live code is a big no-no, so is great for development purposes but it not really usable for a deployed app. To get around this limitation you can implement this patch by the original author.

It is easy to install (even on existing apps), gives you time saving information and in general makes your life easier - all this and it is free! So, if you are not using it, why not?

Friday, 29 July 2011

ASP.NET MVC Hello World

Whilst I do my best to keep up with new programming concepts and techniques the reality is that there is always something new to learn and not enough hours in the day so I am committed to trying to learn at least one new thing a week.

One area I have been wanting to learn more about is ASP.NET MVC which was Microsoft's response to the success of Ruby on Rails. Like Ruby on Rails it is built on the (fairly old) concept of a Model-View-Controller architecture which is a better fit to the Web's natural statelessness than the forced state of standard Web Forms.

I have done plenty of reading on the subject and completed a few small tutorials in the past but never had the time to get to in depth so this week I have been delving deeper into the technology and trying to build a boilerplate solution which I can roll out across projects - you can see the results over on github - this is by no means complete and still has a number of issues but it does include some important elements -
  • Uses ASP.NET MVC 3 with the new Razor view engine and a HTML5 boilerplate template 
  • Error Logging via ELMAH - if you haven't heard of this before it is really worth checking out, I will probably do a blog post on it in the future.
  • LLBLGen Pro 3.1 for O/RM Mapping with some custom template modifications for generating entity interfaces in order to help implement the repository pattern.
  • Inversion of Control and Dependency Injection is handled by Castle Windsor and is so easy to set up but has so many benefits.
  • Built using TDD concepts using NUnit   
One of the hardest things I have found is trying to work out exactly what belongs in which layer, as an example - my initial design required the controller to know about the LLBL entities which created a dependency between the UI and the Data Access Layer which was obviously a bad design so I had to fix that (via the custom LLBL templates).

I will continue to expand the project and hopefully write a follow up post in a few weeks.

Any comments/improvements would be gratefully accepted :)

Monday, 27 June 2011

Black Monday

Well, those that know me will have already heard the news but if not then here goes.

As of today the company I work for has ceased trading and I have been made redundant effective immediately. Exactly what my future holds is still uncertain although I do have some very interesting opportunities which will hopefully allow me to continue where I left off.

I have spent 5 years working for the company and seen it grow from a small 2 man operation into a thriving marketing agency and feel I played my part in that and this feels like a big kick in the teeth. There is a lot more I could say about that but this is not the time or place for that. So instead I would like to take the chance to thank everyone who has made the last 5 years so special both colleagues and clients. Special thanks must go to James (who saw my potential and gave me a chance), Mark, Charlotte, Steve, Helen and Sarah.

So long and thanks for all the fish (or should I say coffee) :(
 

Friday, 24 June 2011

My Top 5 Development Related Apps

Inspired by this Tweet by @netmag from last week, here are the 5 software programs I use for work which I couldn't live without.

  1. Resharper Visual Studio Plugin - I simply could not code in Visual Studio without it, adds all the extra bits that Microsoft forgot about.
  2. LLBLGen Pro - writing database access code by hand is dull and boring, that is just a fact. This marvellous O/R Mapper takes the pain out of it.
  3. Google Chrome - to quote Apple "It Just Works". Fast, lightweight and with a well oiled JavaScript rendering engine make it the best browser out there at the moment.
  4. Spotify - OK, not strictly work related but would struggle to get through a whole work week without it. Despite a few gaps in the catalogue (no AC/DC or Metallica) it is pretty much awesome and all for a £5 month.
  5. Leech FTP - this may be a controversial one with the likes of FileZilla and various others out there. My problem with most of those is that they overcomplicate things - FTP is not a complicated thing and the fact that Leech is no longer being developed means it will continue to remain simple.          

So what do you think? Disagree or have I missed any biggies? Would be interested to know what everyone else thinks.