Avoiding repetitive code using Actions and Funcs

Some coding guidelines require that functions follow a pre-defined scheme, such as

  • log function begin
  • execute function
  • log function end
  • exception handler
  • log exception

to name just the simplest structure.

Since repetitive code is prone to errors, it’s a good idea to encapsulate these steps in a method which in turn calls the “execute function” step.

An example from an MVC project:

public ActionResult Method() {
  logger.Info("begin method");

  try {
    var user = CurrentUser();
    var data = DoSomething(user);
    logger.Info("end method");
    return View("View", data);
  }
  catch (Exception ex) {
    logger.Error("method exception", ex);
    throw;
  }
}

We can now extract most of the code into a common method

protected ActionResult Execute(string actionName, 
  Func<User, ActionResult> action) {
  logger.Info("begin " + actionName);

  try {
    var user = CurrentUser();
    var result = action(user);
    logger.Info("end " + actionName);
    return result;
  }
  catch (Exception ex) {
    logger.Error(actionName, ex);
    throw;
  }
}

so that the original method can be reduced to

public ActionResult Method() {
  return Execute("method", (user) =>
  {
    var data = DoSomething(user);
    return View("View", data);
  });
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.