How to use delegates to remove duplicated code

Sometimes you have duplicated code, that is not easy to remove with “ordinary” coding approaches. Think about the following example. You have two or more methods that needs to be encapsulated with try-catch blocks.

protected void Commit(ObjectMapper mapper, bool nestedTransaction)
{
    if (nestedTransaction)
    return;
    
    try
    {
        mapper.Commit();
    }
    catch (SqlCoreException exc)
    {
        ...
    }
    catch (DirtyObjectException exc)
    {
        ...
    }
    catch (MapperBaseException exc)
    {
        ...
    }
    catch (Exception exc)
    {
        ...
    }
}

protected void Flush(ObjectMapper mapper)
{
    try
    {
        mapper.Flush();
    }
    catch (SqlCoreException exc)
    {
        ...
    }
    catch (DirtyObjectException exc)
    {
        ...
    }
    catch (MapperBaseException exc)
    {
        ...
    }
    catch (Exception exc)
    {
        ...
    }
}

In that case, only the single call changes, everything else does not. So how can we prevent that stupid code duplication? The answer is, by using a delegate method.

private delegate void SafeCallDelegate();

private void SafeCall(ObjectMapper mapper, SafeCallDelegate call)
{
    try
    {
        call();
    }
    catch (SqlCoreException exc)
    {
        ...
    }
    catch (DirtyObjectException exc)
    {
        ...
    }
    catch (MapperBaseException exc)
    {
        ...
    }
    catch (Exception exc)
    {
        ...
    }
}

protected void Commit(ObjectMapper mapper, bool nestedTransaction)
{
    if (nestedTransaction)
    return;
    
    SafeCall(mapper, mapper.Commit);
}

protected void Flush(ObjectMapper mapper)
{
    SafeCall(mapper, mapper.Flush);
}

As you can see, we removed the duplicated exception handling and outsourced it to an new method that takes a Delegate Method as a parameter. This delegate calls the original method. That’s elegant, isn’t it?

I wish you good coding sessions.
Cheers

- Gerhard

kick it on DotNetKicks.com

Posted in .NET, C#. 7 Comments »