Protect your project from dependencies (iOS – swift)

The Issue

Here I will talk about some ways I use to protect my projects against changes in its dependencies.
Whats clear is that every library/framework you use in your project would change at some time, and sometimes we change our mind about these dependencies and replace them with others.

Lets first talk about replacing a library. So we have some library that filter an image, lets call it MOImagesFilter, where you provide it an image and what filter you want to use and then it returns the filtered image. Later you find that this library produce a couple of bugs or does not work well with orientation or 3x screen …. And you decide to use a more famous library called e.g. FastImageFilters! and try it.

But wait …

You already imported MOImagesFilter in 10 classes , and in each class there is a couple of lines related to it. FastImageFilters may have totally different APIs and eventually you find yourself updating 30 lines of code !!! Oo

Adapters to the rescue

The idea here is to point all those calls to one class thats more native to our project where you don’t event need to import it in other classes. That class will be responsible to translate the library we intend to use into one formatted language our project understands.

So we create a class lets call it ImageFiltersAdapter that deals only with MOImagesFilter and does what it does , so we don’t have to deal directly with MOImagesFilter directly at all.
We predefine a set of functions that we actually need from the library , we might not need all of the function , in our case we only needs a function where we give it an image with the intended filter and it returns a filtered image.

Later on if we decide to use FastImageFilters we only change in the adapter class , not all the e.g. 3o lines of code and 10 classes.
Another benefit is that we might not need all the functionalities from some library but just a subset.
Also anyone including you when later tries to understand what we are doing here with the filter class will understand easily instead of going to the original library and read through it.

This not only useful when we replace libraries but also when we update a library where its APIs may have changed.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.