Given a particular third-party class/library you want to make use of, the simplest thing to do would be to just hardcode API calls to it through your application.

On the other hand you have the possibility of defining a interface that generically dictates what you want -not how-, and then follow the Adapter pattern to bind your interface to the third-party class.

I currently feel inclined to the second option because:

  • It creates a single point of change if you ever want to replace the functionality provider

  • In a similar way, it allows you to add more providers without changing your application code

  • It permits following your own naming conventions, simpler method signatures, etc

The thing is, I'm not experienced with this approach and I don't know how complicated or inconvenient it can get. I'd also like to know if are there any common errors when following this pattern.

In my particular case I don't want to wrap either a giantic library -e.g. a GUI- or a small function. Also there are actual possiblities I'll change my provider in the future, so this is not a YAGNI.

Thank you


The dependency inversion principle suggests you should:

High-level modules should not depend on low-level modules. Both should depend on abstractions.

You should write your code against a clear and simple abstraction of whatever external services you may need (i.e. a complex GUI toolkit in your case) and then just write implementations, whether that is by hand or as an adapter for 3rd party components.

| improve this answer | |

You've identified one common error - wrapping the entire interface when you only need a part of it. This will drastically increase the code you write and have to maintain when the dependency changes.

By only wrapping the API calls you actually need you are also defining exactly what it is you want from the dependency. This will help keep things manageable and also allow you to more easily evaluate new providers - do they implement at least the functions you already use?

| improve this answer | |
  • Short yet enough to make the strong points easily understood. +1 – Yam Marcovic Oct 8 '11 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.