Search code examples
dependency-injectioninversion-of-controldependency-inversion

How can I apply the dependency inversion principle when using third party libraries?


I was reading about the dependency inversion principle and as far as I understand the relation is inverted because package A (high level) defines the interface and package B (low level) implements the interface, instead of directly invoking the class in package B.

But how can I apply the dependency inversion principle when I do not own package B? I'm using PHP and through the Composer package manager I import some third party libraries. Since I'm not in control of that code, I cannot make the classes in that library implement my high level interface.

I’ve searched on Google and Stackoverflow but i can’t seem to find questions or articles that mention this use-case.


Solution

  • The standard solution is to write an Adapter over the third-party library. In C#, it would look like the following:

    public interface IFoo
    {
        void Bar(int baz);
        string Qux(bool quux);
    }
    

    This interface would be defined in your A pakcage.

    In another package, you'd reference the third-party library and write the Adapter:

    public class ThirdPartyFoo : IFoo
    {
        private ThirdPartyObject thirdPartyObject;
    
        // Class initialisation goes here...
    
        public void Bar(int baz)
        {
            var corge = // perhaps translate or modify baz first...
            thirdPartyObject.SomeMethod(corge);
        }
    
        public string Qux(bool quux)
        {
            var grault = // perhaps translate or modify quux first...
            var res = thirdPartyObject.SomeOtherMethod(grault);
            var garply = // perhaps translate res
            return garply;
        }
    }