Samantha J T Star
Samantha J T Star

Reputation: 32828

Can I combine replace these methods in derived class with a method in the base class?

I have methods like this:

   public void AddOrUpdate(Product product)
    {
        try
        {
            _productRepository.AddOrUpdate(product);
        }
        catch (Exception ex)
        {
            _ex.Errors.Add("", "Error when adding product");
            throw _ex;
        }
    }


    public void AddOrUpdate(Content content)
    {
        try
        {
            _contentRepository.AddOrUpdate(content);
        }
        catch (Exception ex)
        {
            _ex.Errors.Add("", "Error when adding content");
            throw _ex;
        }
    }

plus more methods that differ only in the class passed to them.

Is there some way that I could code these methods in a base class rather than repeating the method in each derived class? I was thinking something based on generics but I am not sure how to implement and also not sure how to pass in the _productRepository.

FYI here's the way _productRepository and _contentRepository are defined:

    private void Initialize(string dataSourceID)
    {
        _productRepository = StorageHelper.GetTable<Product>(dataSourceID);
        _contentRepository = StorageHelper.GetTable<Content>(dataSourceID);
        _ex = new ServiceException();
    }

Upvotes: 2

Views: 122

Answers (2)

DarthVader
DarthVader

Reputation: 55082

yes you can.

easy way to do is to use interfaces and inheritance. tight coupled

Another way to do is Dependency injection. lose coupled, preferable.

Yet another way is to use generics as follows:

public void AddOrUpdate(T item ,V repo) where T: IItem, V:IRepository
{ 
  repo.AddOrUpdate(item)
}


class Foo
{
    IRepository _productRepository;
    IRepository _contentRepository

    private void Initialize(string dataSourceID)
    {
        _productRepository = StorageHelper.GetTable<Product>(dataSourceID);
        _contentRepository = StorageHelper.GetTable<Content>(dataSourceID);
        _ex = new ServiceException();
    }

    public void MethodForProduct(IItem item)
    {
       _productRepository.SaveOrUpdate(item);
    }

    public void MethodForContent(IItem item)
    {
       _contentRepository.SaveOrUpdate(item);
    }

}

// this is your repository extension class.
public static class RepositoryExtension
{

   public static void SaveOrUpdate(this IRepository repository, T item) where T : IItem
   {
      repository.SaveOrUpdate(item);
   }

}

// you can also use a base class.
interface IItem
{
   ...
}

class Product : IItem
{
  ...
}

class Content : IItem
{
  ...
}

Upvotes: 5

Allan Chua
Allan Chua

Reputation: 10185

Try to use Generic Methods There dude and implement it on your base class you could try this link: http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.80).aspx

Upvotes: 1

Related Questions