Refactoring challenge


I don’t like messy, obfuscated code.  But occasionally often, I write it anyway as I can’t quite see the right way to go.  Today is one of those days where I can’t seem to get past some ugly code, none of my normal tricks seem to work.  Instead of me doing any more work on it, I’m curious if anyone else has any ideas.  Here’s the offending function, in the TypeMapMapper class from the trunk (R97) of the AutoMapper codebase:

public object Map(ResolutionContext context, IMappingEngineRunner mapper)
{
    object mappedObject = null;
    var profileConfiguration = mapper.ConfigurationProvider.GetProfileConfiguration(context.TypeMap.Profile);

    if (context.TypeMap.CustomMapper != null)
    {
        context.TypeMap.BeforeMap(context.SourceValue, mappedObject);
        mappedObject = context.TypeMap.CustomMapper(context);
    }
    else if (context.SourceValue != null || !profileConfiguration.MapNullSourceValuesAsNull)
    {
        if (context.DestinationValue == null && context.InstanceCache.ContainsKey(context))
        {
            mappedObject = context.InstanceCache[context];
        }
        else
        {
            if (context.DestinationValue == null)
            {
                mappedObject = mapper.CreateObject(context.DestinationType);
                if (context.SourceValue != null)
                    context.InstanceCache.Add(context, mappedObject);
            }
            else
            {
                mappedObject = context.DestinationValue;
            }

            context.TypeMap.BeforeMap(context.SourceValue, mappedObject);
            foreach (PropertyMap propertyMap in context.TypeMap.GetPropertyMaps())
            {
                MapPropertyValue(context, mapper, mappedObject, propertyMap);
            }
        }

    }

    context.TypeMap.AfterMap(context.SourceValue, mappedObject);
    return mappedObject;
}

Yes, it’s very, very long. Originally, there were four different exit points all over the place, but that made it difficult to do other things I needed (the BeforeMap and AfterMap calls).  There’s just way too much going on here, so I’m curious if anyone out there in the æther has any other ideas.  Feel free to post ideas here, or for those adventurous folks, submit a patch on the AutoMapper group.  Frankly, it’s making me cross-eyed, so I’ll just turn away in shame.

How not to do Dependency Injection, in NerdDinner