Refactor ThisAnswers

time to read 3 min | 479 words

One of the more interesting results from the replies that I got is that a lot of people didn’t actually read the code.

The major reason that the code was complex was that there were several concerns that had to be dealt with, but the reason that this method dealt with several concerns at the same time was that different actions are required for different errors, that the error handling code itself need to be aware of errors, etc.

One of the nicer suggestions that I got was to create a strategy chain, like this:

public class TransactionBehavior : BaseBehavior
{
    public void Execute()
    {
        using(var tx = new TransactionScope())
        {
            NextBehavior.Execute();
            tx.Complete();
        }
    }
}

public class ExceptionBehavior : BaseBehavior
{
    public void Execute()
    {
        try
        {
            NextBehavior.Execute();
        }
        catch(Exception ex)
        {
            logger.Error(ex.Message, ex);
        }
    }
}

public class ConsumeBehavior : BaseBehavior
{
    public void Execute()
    {
        foreach(var consumer in GatherConsumers())
        {
            reflection.InvokeConsume(consumer);
        }
        NextBehavior.Execute();
    }
}

And that looks really nice, but it suffer from one major problem, it doesn’t (and can’t) handle error scenarios in a good way when different errors have different meanings and requires different responses.

I got some comments that were very critical about the code, but it is quite telling that about 90% of the actual refactoring attempts ended up dropping some critical functionality.

More posts in "Refactor This" series:

  1. (06 Apr 2010) Results
  2. (05 Apr 2010) Answers