Swift Protocol Oriented Programming (POP) #1
Swift have come a long way coming out with great syntax that allows us to make our code very readable. In our day-to-day development routine, we are often faced in a dilemma between these 2 options:
- Making our code readable by refactoring
- Add more code so as to deliver our project on time
The first option probably requires us to walk to our manager to request for more time but enjoy future benefits, while the other probably get you a good thumbs up right away but face chances of being cursed at in the near future.
Robert C. Martin mentioned in his book titled Clean Architecture that we should always deliver features without compromising code quality.
Just like how we always teach the younger ones to practise hygiene, we should also do so in our codebase.
Protocol Oriented Programming (POP)
With this I will now walk you through a very simple example of Swift’s powerful POP that makes our code more readable, reusable and cleaner.
Only classes are allowed to use POP as they all conform to NSObjectProtocol
which is the masterclass of all protocols.
So here, let’s say we have a class call Developer,
class Developer {
var name: String?init(name: String) {
self.name = name
}
}
and we have a protocol call DevelopableInSwift.
protocol DevelopableInSwift { }
Next, we subclass our Developer
class to create a role:
class iOSDeveloper:Developer, DevelopableInSwift { }
then, we use extension to generate our protocol functions,
extension DevelopableInSwift where Self: iOSDeveloper {
func useGuard() { }
}
and finally, we can put it in action!
class ViewController: UIViewController {var developer: Developer { return iOSDeveloper(name: "Lawrey") }override func viewDidLoad() {
if developer is DevelopableInSwift,
let iOSDev = developer as? iOSDeveloper {
print("I am an iOS Developer!")
iOSDev.useGuard()}}}let viewController = ViewController()
viewController.viewDidLoad()
Looking at these codes, we can easily identify the reason behind the codes written, an iOSDeveloper
object was created such that it can conform to a set of reusable methods that can be use project-wide.
And in the near future, when your manager comes to you with a new feature like we also need to track Android Developers
, then we can add:
protocol DevelopableInKotlin { }class AndroidDeveloper:Developer, DevelopableInKotlin { }
and …
extension DevelopableInKotlin where Self: AndroidDeveloper {
func isNullSafe() -> Bool { return true }
}
and putting everything together in a playground:
Conclusion
POP is wonderful, POP is amazing. It helps us to make code more readable and fun to write. This story is written with inspiration from a great introduction of POP by Natasha here.
This is just one of the million ways we can implement POP in our code. As the project scales, you will be thankful that you have started this approach as making changes and finding what you code previously will be more seamless and convenient. Happy POPing!