Database Abstraction Layer for iOS

Samvel Pahlevanyan
3 min readNov 26, 2019

--

Almost in all the new software projects, we need to use persistent database storage, and here comes the same question — how do we strive for a balance between future complexity and current usability.

As a developer, you should consider the possibility that the database you are using today, may be inappropriate in the future. Are you ready to rewrite your project? If your answer is NO, then you are on the right path.

Today, we are going to look at one abstract layer that allows us to easily “Switch” to a new database. You can download an example project from GitHub.

I hope you know about SOLID, because we’re going to use one of the principles calledDependency inversion

Dependency inversion principle states:

High level modules should not depend on low level modules; both should depend on abstractions. Abstractions should not depend on details. Details should depend upon abstractions.

Let’s start.

Let’s look at the example where we need to create users, store them in our local DB.

First of all, we need to create User class.

But it is also necessary to classify those models that will use our Abstraction layer, for that we need to create an empty Protocol called Storable and extend our user class.

Every class should be extended from Storable if you want to save it to DB.

Now it’s time to create our abstraction layer called StorageContext, and define all the functions we want to have.

So let’s see what we have created.

User — The model we want to save to DB.
Storable — Abstraction for every model we want to save it to DB.
StorageContext — Abstraction for a specific DB.

Now we have all the necessary components and can create low level module called RealmStorageContext, inherit from StorageContext and implement all the functions that are presented on it.

Now we have everything ready and we can use it.

Conclusion

In the beginning, we discussed a problem where our project depended on a specific DB.

For the solution we used one of the SOLID principles called Dependance Inversion.

Our project became independent from DB and DB became independent from the project, both became dependent on the abstraction, and at some stage of programming we can make use of another DB with little changes.

Thanks for reading! If you liked this article, please clap, so that the others can also read it :)

📝 Save this story in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--

Samvel Pahlevanyan

iOS programmer with a seven-year track record of commended performance in object-oriented programming. Well-versed in all phases of software development.