Wrap Methods With Same Frame Functionality

Sometimes one have to write several methods in one class having the same “frame” functionality, e.g. a try/catch block with logging inside the catch.

Instead of copying this try/catch block all the times, one can create a wrapper for these methods. The goal is to have the try/catch block only written once.

The only thing needed in addition is to declare a delegate. This is how it works:

Declaring the delegates:

/// <summary>
/// Delegate for a processing step with no return value.
/// </summary>
private delegate void ProcesstingStep();

 

/// <summary>
/// Delegate for a processing step with a boolean return value.
/// </summary>
private delegate bool ProcesstingBooleanStep();

Declaring the wrapper:

/// <summary>
/// Do a process step on a method without return value.
/// </summary>
/// <param name=”processingStep”>The step to process.</param>
/// <returns><c>true</c> if no exception occurred, otherwise <c>false</c>.</returns>
private bool ProcessStep
  (
  ProcesstingStep processingStep
  )
{
  try
  {
    processingStep();
  }
  catch (Exception e)
  {
    MessageBoxHelper.ShowError(MessageboxOwner, e.ToString());
    return (false);
  }

  return (true);
}

 

/// <summary>
/// Do a process step on a method with a boolean return value.
/// </summary>
/// <param name=”processingStep”>The step to process.</param>
/// <returns><c>true</c> if the method succeeded and no exception occurred, otherwise <c>false</c>.</returns>
private bool ProcessStep
  (
  ProcesstingBooleanStep processingStep
  )
{
  try
  {
    return (processingStep());
  }
  catch (Exception e)
  {
    MessageBoxHelper.ShowError(MessageboxOwner, e.ToString());
    return (false);
  }
}

Calling the methods:

 

if (!ProcessStep(new ProcesstingBooleanStep(ValidateInput))
  || !ProcessStep(new ProcesstingStep(LoadProjectDocument))
  || !ProcessStep(new ProcesstingBooleanStep(GetBasePath))
  || !ProcessStep(new ProcesstingBooleanStep(LoadContentTemplate))
  || !ProcessStep(new ProcesstingStep(LoadMenuItems))
  || !ProcessStep(new ProcesstingStep(LoadCssClasses)))
  {
    return;
  }

Since .NET has evolved, maybe you want to use Action<> or Func<> now instead of self-defined delegates ;-).