views:

33

answers:

2

Hi folks, I have a bunch of asmx web services, and in all the methods inside the webservices follow a common pattern

public virtual TestObject Test()

{
   LogRequest;
   try
   {
    DoSomething;
   }
   catch
   {
     LogException;
   }

   LogResponse;
   return response;
}

and all the methods follow this pattern, there is a lot of code repetition; I want to know if there is a way to do this generically ie: may be in a base class constructor? is it even possible?

+1  A: 

You can have a method somewhere (in a base class or declared static anywhere) that does all the common stuff:

T DoCommon<T>(Request r, Func<T> f)
{
  LogRequest(r);

  T result;
  try { result = f(); }
  catch(Exception ex) { LogException(ex); } 

  LogResult(result);
  return result;
}

And then you'd only have to include a call to that method:

public virtual TestObject Test()
{
   return DoCommon(Request, () => DoSomething());
}
Mark Cidade
A: 

It sounds like you're looking for the Template Method pattern. That pattern allows you to define a series of steps in the superclass (and default implementations of those steps, if applicable) - then subclasses need only override the steps relevant to their specific processing.

mikemanne