An example of Protocol-Oriented Programming in Swift
Have you ever heard about Object-Oriented Programming ? Yes, of couse. OOP is very common nowaday.
But, how about Protocol-Oriented Programming ?
Protocol-Oriented Programming (POP) was first introduced by Apple in WWDC 2015 with Swift 2.0, and they called Swift is POP, not OOP like others common language: Java, Python, C#,…
You may wonder: What the hell is POP ?
1. What is POP ?
Actually, we do not have any official document to define POP, but it is OK. Let's have a closer look at its naming and compare: Protocol-Oriented Programming with Object-Oriented Programming. Clearly, they have a small difference from their Prefix: Object & Protocol. Now, try to imagine and think about Object-Oriented Programming: What is it? Why do we call it OOP?
In OOP, we design and focus on "Class", and its instance called "Object", which may contain data, property, method, implementation, …
→ In Object-Oriented Programming, we focus on Object.
→ We may infer: Protocol-Oriented Programming, we will try to working with Protocol.
"Instead of using a class, start with a protocol"
2. An example of POP ?
Because, POP is the substitution of OOP, POP has many advantages over OOP. Nowaday, in Swift, i see people prefer using Struct combine with Protocol (usally use in POP) rather than using Class (OOP). Every thing Class can do, Struct can too, Struct base on Value Type instead of Reference Type in Class → we may avoid memory leak, implicit sharing data, deadlock (multithread), …
It is not all about POP and OOP, we will go to a pratical example.
I have a class called Bird, Bird has 2 properties: name and feather.
Then, i have 2 subclass of Bird, illustrate for Parrot and Eagle.
But now, i want to add Penguin. Oops…….
Penguin is a bird, but Penguin does not have feather, and cannot fly. Sad for my little Penguin :(.
How to fix now? In OOP:
- Decouple to : Bird and Penguin Class → Oops, bad idea.
- Create Protocol illustrate for Flyable → we have to re-write many code
- change to static func fly() → in case we have 10–100 subclass???
3. Welcome to POP:
We can re-design our base code, change from Class to Protocol and Struct to solve this problem.
With Extension, we do not need to rewrite many code, just when we need to modify or in some special behavior of flying.
As you see, Penguin does not to implement Flyable and Featherable and does not break our design and structure. Cheers to my happy little Penguin.
You can try to add new Bird, like Ostrich (cannot fly, but Ostrich has feather) and see the magic.
Conclusion, with my sample, i hope you can have a smart look at Protocol-Oriented Programming. Of course, POP just be a concept, you can apply it if you want, or you do not need to apply it, depend on your decision and your problem. If you want to read more about this topic, there are some good links: