Jamie
Jamie

Reputation: 321

how to avoid duplicating code (design pattern)

I have several methods in a class that has the same logic but I can't see how to avoid the duplication? Each method internally calls another service but otherwise the logic before and after the internal service call are the same, see the code snippet below.

Any help appreciated!

Many thanks,

code

public List<Customer> GetCustomerDetail(int id)
{
  _log.debug("xxx");

  if(something)
  {
    _log.debug("yyy");
  }

  var results = _internalService.GetCustomer(id);

  if(results == null) 
  {
    _log.debug("no results");
  }

  return results;
}

public List<Customer> GetCompanyDetail(int id)
{
  _log.debug("xxx");

  if(something)
  {
    _log.debug("yyy");
  }

  var results = _internalService.GetCompany(id);

  if(results == null) 
  {
    _log.debug("no results");
  }

  return results;
}

...

Upvotes: 0

Views: 136

Answers (2)

C. Rahn
C. Rahn

Reputation: 301

Use delegates:

public List<Customer> GetCustomerDetail(int id)
{
    return DoIt( () => _internalService.GetCustomer(id) );
}

public List<Customer> GetCompanyDetail(int id)
{
    return DoIt( () => _internalService.GetCompany(id) );
}

private T DoIt<T>( Func<T> func )
{
  _log.debug("xxx");

  if(something)
  {
    _log.debug("yyy");
  }

  var results = func();

  if(results == null) 
  {
    _log.debug("no results");
  }

  return results;
}

Upvotes: 5

AgentFire
AgentFire

Reputation: 9780

Several options, depending on the duplication density:

  1. Do nothing. Two-three dups probably not worth time spending on them
  2. Make some string constants/readonly fields, if you want. That'll remove some magic strings from the code as well as allow you to neatly change them.
  3. Add logging methods to the (2), that's what is recommended if you duplicate hard.

Upvotes: 0

Related Questions