<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by radhakrishna pai on Medium]]></title>
        <description><![CDATA[Stories by radhakrishna pai on Medium]]></description>
        <link>https://medium.com/@radhakrishnapai09?source=rss-9f9b9f934902------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*11gMYvEF7566iZlG.jpg</url>
            <title>Stories by radhakrishna pai on Medium</title>
            <link>https://medium.com/@radhakrishnapai09?source=rss-9f9b9f934902------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:09:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@radhakrishnapai09/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PROTOCOL-ORIENTED PROGRAMMING]]></title>
            <link>https://medium.com/@radhakrishnapai09/protocol-oriented-programming-45db7ce2519?source=rss-9f9b9f934902------2</link>
            <guid isPermaLink="false">https://medium.com/p/45db7ce2519</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[radhakrishna pai]]></dc:creator>
            <pubDate>Sat, 02 Feb 2019 10:41:32 GMT</pubDate>
            <atom:updated>2019-02-02T12:25:41.250Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Protocol-Oriented Programming</strong></h3><p>Part 1<strong> — Swift, </strong>GoGreen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*6uQfjphH8FaPUaLNXsH5SQ.png" /></figure><p>Hello There!</p><p>It’s a wonderful chilly day. The perfect weather to have a hot cup of coffee ☕and something to read along. What say Let’s learn something new while we are at it?</p><p>Well it’s actually not new and has been around for more than 3 years. But for those of you who have still not heard about it, read on! I’m sure you will enjoy it!</p><p>Today’s topic is Protocol-Oriented Programming (POP) in Swift. It was first introduced by Apple in their <a href="https://youtu.be/g2LwFZatfTI">WWDC</a> session way back in 2015.</p><p>Before going into the details of POP, let’s discuss a lil about Object Oriented Programming (OOP).</p><p>OOP is awesome! Classes are awesome! Right??? 😅 If you are an Obj-C based techie like me then im sure you will agree.</p><p>OOP has been around for ages. We have all made wonderful things based on classes and objects. In Fact we are all so consumed by it that it is so hard to think of a different way right? Well I thought so too. But not any longer..</p><p>First Let me list out a few features of classes.</p><ul><li>Encapsulation</li><li><strong>Access Control</strong></li><li><strong>Abstraction</strong></li><li><strong>Namespace</strong></li><li>Expressive Syntax</li><li>Extensibility</li></ul><p>Classes give me all these features and much more. I would like to bring your attention to the highlighted points.</p><blockquote>“These things let us manage complexity. And that’s really the main challenge in programming. These properties directly address the problems that we are trying to solve in software development.”</blockquote><p>Feeling so proud and mighty?</p><p>Well what if we can do all these using Types: Structs and Enums.</p><p>Yes you heard me right 😐. In Swift, any type you can name is a first class citizen and is able to take advantage of all of these above mentioned capabilities.</p><h3>Classes are Awesome!??</h3><p>Why did we stick along with classes all this while? There has to be something that we can do only with classes. Like inheritance.</p><p>For example: A superclass can define a method with complex logic and subclasses get all of the work done by the superclass for free.</p><p>But the real magic happens when the superclass author breaks a tiny piece of that method to a separate customization point, which the subclasses can override. This way you get to use the method with the difficult logic already done for you and all you need to do is reuse it according to your needs by applying your changes to it. This way the superclass gives open ended customization and flexibility.</p><p>Well if you are sticking to classes just for customization, I would say you can achieve the same through structs. Classes are powerful but at what cost?</p><h3>3 Beefs with Classes</h3><h4>1. Implicit Sharing</h4><p>Classes are reference types. Data is always shared between classes implicitly. If two classes are sharing some data say, ‘Package’, one class is unaware when some change is made to ‘Package’ by the other class. Later at some point in time, if the second class tries to access ‘Package’, it might get a totally different thing.</p><p>You would say we can stop this by copying the data.</p><p>The sad story.. Defensive copying leading to.. inefficiency.. Leading to race conditions.. then you apply locks.. which leads to more inefficiency.. and may be dead locks.. and more complexity.. Which leads to….BUGS! 🐛🐞🕷</p><p>Well this is not news to COCOA programmers 😎. We have been applying language features like @property (copy), and coding conventions over the years to handle this. And we still get bitten. For example there is this warning in <a href="https://developer.apple.com/documentation/foundation/nsenumerator?language=objc">COCOA documentation</a> about modifying a mutable collection while iterating through it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*1yoe1kyoeAMlwavy" /></figure><p>But this doesn’t apply to swift because swift collections are value types. Values don’t share. (that’s a good thing). Classes? They overshare.</p><h4>2. Class inheritance is too intrusive</h4><p>You can choose one and only ONE superclass. So since only single inheritance is allowed classes get swollen as everything that might be related to is thrown together. You have to choose your superclass while defining your class and not later in some extension.</p><p>If your superclass has stored properties, you have to accept them. Then it’s your burden to initialize them as well. You have to understand how to work with your superclass without breaking its invariants.</p><p>Also, it’s your responsibility to know when/how to override methods and when not to. There is this unwritten contract about what is allowed and what is not.</p><p>Again, This is not news to COCOA programmers 😎(😥)</p><p>This is exactly why we use the delegate pattern throughout our code in COCOA.</p><h4>3. Lost type Relationships</h4><blockquote>“Classes turn out to be a really bad fit for problems where type relationships matter”</blockquote><p>Suppose you are trying to use classes for a symmetric operation like comparison. For example, you want to write a generic function for binary search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*WqJP3ToOjmqtk45_" /></figure><p>But Swift demands a method body for ‘precedes’ as you can see above. So what can we put there? At this point, we have no idea what an arbitrary instance of ‘Ordered’ might be. So if the method is not implemented by a subclass, there is really nothing much we can do other than something like..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/0*GG5M4Z_yTdS3-c1o" /></figure><p><em>“This is the first sign that we are fighting the type system.”</em></p><p>If we fail to recognise this, then it is also the point where we start lying to ourselves. ‘Cause we rush aside our problem and dump it on the subclass. As long as every subclass of ‘Ordered’ implements ‘precedes’, we are safe.</p><p>So we press ahead and try to write an implementation of ‘Ordered’ say as follows..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*DLxOC-5fTeg-ZOG6" /></figure><p>Here we create a class ‘Number’ with a Bool var ‘value’. In the implementation of ‘precedes’ we return by comparing this var ‘value’. But ‘other’ doesn’t have a var property. In fact ‘Ordered’ is supposed to be a generic class and so it can even be a label..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*kALwASJSokmLEzWA" /></figure><p>So we will have to downcast ordered into ‘Number’ type as follows to get rid of the error..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*4bYc3SFJMu0jPdmi" /></figure><p>But wait, what if we actually want to pass a label in precedes instead, or as a matter fact, any type that is a subclass of ‘Ordered’ should work.</p><p>This is starting to smell much like when we started with this problem. We don’t have a better option now than we did before.</p><p>This is called a ‘static type safety hole’.</p><p>It happened because classes don’t let us express this crucial type relationships between the type of ‘self’ and the type of ‘other’. In fact you can use this as a code smell.</p><p>Whenever you see a forced downcast in your code like:</p><p><strong>as ! ASubclass</strong></p><p>It is an important…</p><blockquote>“Sign that some crucial type relationship is lost. Usually due to using classes for abstraction”</blockquote><p>But … but.. Classes were awesome 😢😭..</p><p>There there. It&#39;s ok. Classes are still awesome in the situations where they are intended to be. But the above mentioned issues clearly pronounce that we need a better abstraction mechanism.</p><ul><li>One that doesn’t force us to accept implicit sharing</li><li>One In which type relationships are not lost</li><li>One that doesn’t force us to choose one abstraction and do it at the time we define our types</li><li>One that doesn’t force us to accept unwanted instance data or the associated initialization complexity</li><li>One that doesn’t leave ambiguity about what we need to override</li></ul><h3>Enter Protocols!!!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*XbsZUWAiuwV559RtPk1uLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Nzy5fClWD_BnBCmfelB8HA.gif" /></figure><p>Protocols have all the previously mentioned advantages, and Apple proudly states that this is why,</p><blockquote><em>“When we made Swift, we made the first Protocol-Oriented Programming Language”</em></blockquote><p>From the way for loops and string literals work to the emphasis in the standard library on generics, at its heart, swift is protocol-oriented. And hopefully by the time you finish reading this series, you will be more protocol oriented yourself.</p><p>So to get you started on the right foot, there is a saying in Swift,</p><blockquote>“Don’t start with a class. Start with a protocol”</blockquote><p>Let’s try that with our previous example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*2xUAitoNNDQNnJql" /></figure><p>As soon as you change the ‘Ordered’ class to a protocol you will come across this error saying, “Protocol methods must not have bodies”, which is good, ‘cause now we get rid of the ugly mandatory definition as in the case when using a superclass. Also you get a static check instead of a dynamic check to see if the method is implemented.</p><p>Next you will get an error in our ‘Number’ class, saying ‘precedes’ “Method does not override any method from its superclass”. We don’t have a base class anymore, so no superclass, no override.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*udLEtKlW6NWDYYbN" /></figure><p>Let’s get rid of the method definition in the protocol, and the override keyword in ‘Number’. Maybe we didn’t want Number to be a class in the first place ‘cause we want it to act like a Number. So let’s make that a Struct.</p><p>After all these changes, you will have this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*VD6sU_55SE_nKlrT" /></figure><p>I wanna stop for a moment and appreciate where we are.. 😎 ..yea.. ‘cause this is all valid code again!</p><p>It’s definitely better, we got rid of the fatal error, and we achieved it without using classes. But still there is the forced down cast which looks ugly. So let’s fix that by changing type of ‘other’ parameter to ‘Number’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*L9FxiAZYD4r7fRKF" /></figure><p>Now it will complain that ‘Number’ does not conform to the protocol ‘Ordered’ due to mismatch in parameter type. Let’s fix that by doing this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*gdeOgIlk0RtAJPGT" /></figure><p>Voila! It looks beautiful, doesn’t it ? 😍</p><p>This is called a ‘Self’ requirement.</p><blockquote>“Whenever you see ‘Self’ in a protocol, it’s a placeholder for the type that is going to Conform to that protocol, the model type”</blockquote><p>Now we have valid code again. Let’s take a look on how we use this protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*jsH0rYLR5PAOsGeB" /></figure><p>This is the binary search that worked when ‘Ordered’ was a class. In fact it worked until we added that ‘Self’ requirement.</p><p>The ‘sortedKeys’ array in the method, is a claim that we will handle a heterogeneous array of ‘Ordered’. So it means the array could contain say number and labels mixed together. Right? (😅 yea right. How on Earth do we handle that though? 😓)</p><p>But now that we have added this ‘Self’ requirement, the compiler is gonna force us to make this homogeneous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*kWPzQk7DO6vcmJ8N" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*92n_u1tWoM_Xyz8B" /></figure><p>So, let’s make that generic shall we?</p><p>Here we go..3..2..1.. Poof!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*XkeynmToeola4NnG" /></figure><p>This one says, “I work on a homogeneous array of any single Ordered type T”.</p><p>Now you might say that forcing the array to be homogeneous is “too restrictive” or a “loss of functionality” or “no flexibility” or something, but if you think about it, the original claim was really a lie. 😶</p><p>Hey stranger, we never really handled the heterogeneous case other than by trapping using the ‘fatalError’. Uh-huh? 😏</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*dcfxwT6eMGnbafn0" /></figure><p>There there, Don’t cry. I am not trying to prove you wrong, but we have to let go of the past and our beliefs if we need to move on and learn something new. 😊</p><p>So like I said, we never wanted a heterogeneous array since we were not actually handling it at all. A homogeneous array is what we want.</p><p>Once you add a ‘Self’ requirement to a protocol it moves the protocol into a very different world where the capabilities have a lot less to overlap with classes.</p><p>Let’s list the differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1AwK3MVKe2HNct_yJv4hA.png" /></figure><p>Two worlds!</p><p>Later I will show you how to build a bridge between them, at least one way.</p><p>Winding up, I hope this has helped enough that the next time you use classes for abstraction, you will definitely think again.</p><p>Also I hope you have understood how the static aspect of protocols work. I have barely scratched the surface, there is still a lot to discuss! If you wanna know more, stay tuned for <strong>Part 2 </strong>of this series.</p><p>Enjoy your coffee! ☕ (if still left.. if you forgot about it. 😅)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45db7ce2519" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>