views:

967

answers:

2

Scenario:

(If anyone has answered/viewed my questions recently this will be somewhat familar)

I have 3 different web services which expose a set of objects that have commonality. I've written wrapper classes and conversion logic using generic methods to change between the intermediary objects and the service object.

I have an interface for the Webservice, let it be called IService for the purpose of this question. I have 3 implementation classes Service1Impl, Service2Impl and Service3Impl. Each of these referencing a different web service and using my aforementioned generic methods to convert between the appropriate objects.

These are injected into my ServiceWrapper class at runtime via the constructor (a factory is used to create the appopriate implementation of the ISerivice

e.g:

_service = ServiceWrapper.GetServiceWrapper("2");

Will give me a ServiceWrapper instantiated with the Service2Impl.

(Dammit diagrams would be hella useful!)

Ok so each implementation of IService has a method called for arguments sake.. GetProperties:

public IProperty[] GetProperties(string item, IProperty[] properties)
{
    Property[] props = ServiceObjectFactory.CreateProperties<Property>(properties);
    Property[] result = _service.GetProperties(item, props);
    return ServiceObjectFactory.CreateProperties(result);
}

This looks a little confusing (I think I'm going to refactor the names).

Basically what is happening is:

  1. The call to this function from ServiceWrapper is made with the intermediary objects (IProperty) (as you can see from the parameters).

  2. The intermediary objects are converted to Property objects which are service specific.

  3. The result comes back as service specific Property objects.

  4. The result is converted to the intermediary objects before being passed back to the ServiceWrapper.

Now, this code is going to be exactly the same for Service1Impl, Service2Impl and Service3Impl. Except of course that the types used are different.

Can anyone think of a way to do this so that I don't have the same code 3 times?

N.B: This is not true of every method in each Implementation. Just most of them.

A: 

I am not sure if it fits to your scenario but reading through your question Inversion of Control comes me on mind.

Jakub Šturc
+1  A: 

I think in general, if you want your code to have different type signatures, you'll have to write the code three different times. Since the types are different, it's not "the same code" at all.

You could put what you have into an inherited method and then wrap the results in each subclass.

Steven Huwig
That's what I was thinking atm. Thanks.
Rob Stevenson-Leggett