Featured post

How Dependency Inversion is applied in iOS


Have you ever encountered in your college years the topic about Dependency Inversion Principle? In object-oriented programming, the principle refers to a specific form of decoupling software modules (as what wiki stated: https://en.wikipedia.org/wiki/Dependency_inversion_principle)

High-level Modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details, rather Details should depend on abstractions.

during my college years, this concept seems really valuable, but never have I able to practice it. It's when we put this principle into practice that we can realize how much it can help in developing the structures of our projects. As to many development principles, decoupling is one of the most important aspect in designing our code, and this principle solves this challenge. But how can we apply this principle in our iOS Project?

Actually we don't need to start from scratch in creating classes that follows dependency inversion. In fact, Apple encourages us to use this pattern.

The Delegation Pattern



The delegation pattern is one of the most common patterns use through out iOS applications. If you ever came across using the UIImagePickerController and implemented its methods to conform - you're already following the dependency inversion principle.

Again when we read through this:
High-level Modules should not depend on low-level modules. Both should depend on abstractions.

The High level module is the UIImagePickerController - this module can stand on its own, and it has a framework of functionalities (which is the abstraction). But the usage of its functionalities is not yet define. That's the time the low-level modules will now define (this is your code)

Abstractions should not depend on details, rather Details should depend on abstractions.

Notice this also, when you're using a class or module in iOS which requires you to conform a protocol, your classes are required to implement its methods. i.e, UITableViewDatasource, UItableViewDelegate, UIImagePickerController and more.

So how does this knowledge help?Even though Apple has already provided us classes with dependency-inversion-ready classes, there will be a time in our development when our company wants us to create modularize classes, which can be reuse in other projects. (well, yeah to save time and money for future projects.)

With dependency-inversion mindset, we can refactor some of our old projects and maybe extract from there reusable modules. It would be, like the Location Picker, or a Custom Camera Controller that you really love. You can even make modules that follows a certain standard or feel of your company.

Comments