Using third-party libraries – always use a wrapper

encapsulationthird-party-libraries

Most projects I am involved with use several open-source components. As a general principle, is it a good idea always to avoid binding all components of the code to the third-party libraries and instead go via an encapsulating wrapper to avoid the pain of change?

As an example, most of our PHP projects directly use log4php as a logging framework, i.e. they instantiate via \Logger::getLogger(), they use ->info() or ->warn() methods, etc. In the future, however, a hypothetical logging framework may appear which is better in some way. As it stands, all the projects which closely couple to the log4php method signatures would have to change, in dozens of places, in order to fit the new signatures. This would obviously have a wide impact on the codebase and any change is a potential problem.

To future-proof new codebases from this kind of scenario, I often consider (and sometimes implement) a wrapper class to encapsulate the logging functionality and make it easier, though not foolproof, to alter the way in which logging works in future with minimal change; the code calls the wrapper, the wrapper passes the call to the logging framework du jour.

Bearing in mind that there are more complicated examples with other libraries, am I over-engineering or is this a wise precaution in most cases?

EDIT: More considerations – using dependency injection and test doubles practically requires that we abstract out most APIs anyway ("I want to check my code executes and updates its state, but not write a log comment/access a real database"). Isn't this a decider?

Best Answer

If you only use a small subset of the third party API, it makes sense to write a wrapper - this helps with encapsulation and information hiding, ensuring you don't expose a possibly huge API to your own code. It can also help with making sure that any functionality you don't want to use is "hidden".

Another good reason for a wrapper is if you expect to change the third party library. If this is a piece of infrastructure you know you will not change, do not write a wrapper for it.

Related Topic