views:

74

answers:

3

I have an email component that I am integrating into my application, looking for some tips on how should build a wrapper around it so I can swap it out with another 3rd party component if needed.

My approach right now is it:

  1. build an interface will the functionality I need.
  2. create a class that implements the interface, using my 3rd party component inside this class.
  3. any usage of this component will be via the interface so like:

    IPop3 pop3 = new AcmeIncePop3Wrapper(); pop3.connect();

and inside AcmeIncePop3Wrapper will be:

   public void connect()
   {
         AcmeIncePop3 pop = new AcmeIncePop3();
         pop.connect();
   }

Is that a good approach?

I could probably add another abstraction by using ninject so I could swap out implementations, but really this seems to be all I need as i don't expect to be changing 3rd party assemblies every day, just don't want to make things so tightly coupled.

A: 

I'd say your implementation is fine, that's exactly the sort of thing I'd do to wrap something.

Ian
+1  A: 

You're on the right lines.

Simply using an interface wouldn't solve it, as you can't add the interface to the definition to the class you need if it is located in a 3rd party assembly. Instead, do one of two things:

  1. create a whole new class with methods common to all the different assemblies you know of, and handle each different assembly that can exist (additional logic might be needed here to handle major differences).

  2. create an interface with common methods etc., then create a new class that inherits from the 3rd party class and implements the interface. Do this for each class in new assemblies that you need to use.

The problem with option 2 is that you can't extend a sealed class, which I would expect a third party to do. I recommend option 1.

Codesleuth
+1  A: 

I think you have a good implementation. Basically your interface says "This is how I want to deal with email" and the third party components may do things differently, but if you build your wrapper classes based on your interface you should be able to work any third party component into that interface.

The only thing you may want to watch out for is where you are newing up the concrete classes. You could consider using a factory or something if you're newing it up alot - if not it may not be a big deal. I'm just thinking that if you create new AcmeIncePop3() all over the place then it's still rather tightly coupled to that concrete class.

Ryan Elkins
good idea, so I can create a method that does something like: GetPop3Object(), so I have to change code in one place to swap implementations.
mrblah
Yeah, that's the idea. I'm not really sure what the best way to go about implementing it would be. Look into the Factory pattern for more details.
Ryan Elkins