Composition and Inheritance OOP concepts at work!
Hi guys, today I gonna talk about OOP Composition and Inheritance concepts and how we can solve the main inheritance problem. If you want to resolve duplication of code, you need an ability to share this code is some way and programming languages have a few mechanisms for that. Tho main of them — Inheritance and Composition concepts. So let’s dive into a small iOS Swift project!
Check my other related post about the duplication DRY OOP concept: https://medium.com/@alexalmostengineer/dry-principle-of-software-development-common-mistake-ef014d8f389e
It’s easy to understand on a mini-project. So for example, we need functionality to show UIActivityIndicatorView and change the background of the current controller to dark/light style on any page where it will be needed.
You can see a few methods that should be shareable. With inheritance, we can
simply add these methods to some base, for example, ViewController class.
For example, we have 2 classes FirstViewController and SecondsViewController. And now both of them can inherit ViewController.This method is reusable now and we can call all of these methods (except private) in our 2 subclasses. So it is nice, so what the problem here?
The method above is nice but when the project will become larger, our ViewController will have 20 or 30 global reusable methods. For example, we don’t need an UIActivityIndicatorView logic and we just need only change background logic in our SecondViewController (or what is worse, we need only 2 methods from 30 global for example). But is impossible to inherit only one specific method or for example, create multiple classes and to inherit a few of them. As a result, we will have a small class that was inherited from a massive base ViewController with 30 methods which will be unused.
And It’s time for Composition!
A class can inherit several protocols, unlike several classes. Let’s create 2 protocols — Loaderable and ChangebleBackground for our needs:
So the main feature here is that protocols have default values in the extension section and that’s why we don’t need to implement these methods in each class which will conform to these protocols.
As you can see, SecondViewController doesn’t know about loader logic and because it only conforms to ChangeBackground protocol. So it is easy to separate logic to different protocols and conform only protocols that you need in the current class.
Inheritance is a useful mechanism but is good to use it only for very global things that were needed in all subclasses
Composition helps us to separate shareable logic to different protocols and use only needed protocols in each concrete place.
There are no wrong or right concept — we just need to combine them and inherit global logic and try to composite variable logic in different protocols.
Check this example on my Github here