Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Pattern for abstract class specific code

I have an abstract "Action" class, which has derived types of ActionAppointment, ActionCall, ActionEmail, and ActionLetter. I'm trying to write a function that will DRY up our service layer, so we're not writing CRUD calls 5 times anymore.

I have in our service layer some update logic (lots of other code removed for brevity):

private IServiceResponse UpdateAction<T>(T action, string originalActionStatus) where T : Action
{
        if (action.GetType() == typeof(Action))
        {
            _actionRepository.Update(action);
        }
        else if (action.GetType() == typeof(ActionAppointment))
        {
            _actionAppointmentRepository.Update(action as ActionAppointment);
        }
        else if (action.GetType() == typeof(ActionCall))
        {
            _actionCallRepository.Update(action as ActionCall);
        }
        else if (action.GetType() == typeof(ActionEmail))
        {
            _actionEmailRepository.Update(action as ActionEmail);
        }
        else if (action.GetType() == typeof(ActionLetter))
        {
            _actionLetterRepository.Update(action as ActionLetter);
        }
}

Unfortunately, how our repositories are setup, I have to use the specifically named repositories (ie. I can not update an ActionLetter through the _actionRepository even though it derives from Action)

I have been reading on different patterns, and it sounds like something similar to a Factory Pattern, but I can't see how to make it work.

Am I missing something stupid?

like image 459
mandreko Avatar asked Jun 23 '11 20:06

mandreko


1 Answers

Can't you just write an overload of that method for each action type? Forget the <T> and typeof stuff - what you're doing is implementing a built-in language feature (method overloading) by hand, and in a fragile way too.

like image 183
Matti Virkkunen Avatar answered Sep 24 '22 18:09

Matti Virkkunen