Last updated: 4 months ago
About: Make types that confirm to a protocol have private fields
Story of how I came up with this, or, Use Cases: I had 2 different Video players in my app, a library ASPVideoPlayer, and another AVFoundation's AVPlayer. I had table view cells which contained videos, like instagram. And I wanted them to auto play when user scrolled. The Abstraction: A Protocol VideoPlayable, which had 2 methods, play() and pause(). For ViewControllers which had ASPVideoPlayers, a protocol inheritance ASPVideoPlayable, from VideoPlayable, which I wrote a default method (protocol extension) of interacting with that player. And same for AVPlayer's protocol extension. These 2 protocols ASPVideoPlayable and AVVideoPlayable had one more requirement of a variable player, of that type. Now since the player variable is in protocol requirement, it's implementation had to be internal access level. But there were code reviews and the seniors did not allow me to expose the player variable. I was advised to provide a default implementation in a subclass of UIViewController, which rang like red flags in my head. My knowledge of Composition from RW, PointFree.co, Objc.io and Eric Elliot's book Composing Software is not in lines with the solution provided. Hence, I came up with a solution, that the code in protocol extension can be copy pasted in all the class files confirming to that protocol. The Copy-Paste boilerplate generation was done using Sourcery. And after implementing this solution, flew past code reviews swiftly!
Trivia: 1. After discovering this pattern, I've used it 3 times. 2. I have created a monorepo which contains Sample project, Slides, and Instructions on achieving the same: https://github.com/Viranchee/PrivatePropertiesInProtocols 3. I held a talk at the local community for the same last month
By the end of this talk, the audience will: Learn Protocol Inheritance, Meta Programming, few Swift syntax sugars, be encouraged to think out of the box during tricky situations