<?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 Milan Nosáľ on Medium]]></title>
        <description><![CDATA[Stories by Milan Nosáľ on Medium]]></description>
        <link>https://medium.com/@milan.nosal?source=rss-c8da7c5c84a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L0TQ4iCBTz6ZDGAjfxbQIQ.jpeg</url>
            <title>Stories by Milan Nosáľ on Medium</title>
            <link>https://medium.com/@milan.nosal?source=rss-c8da7c5c84a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:34:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milan.nosal/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[Swift Protocol-Oriented Programming: New Paradigm or Yet Another Hype?]]></title>
            <link>https://medium.com/@milan.nosal/swift-protocol-oriented-programming-new-paradigm-or-yet-another-hype-59e9b7ddc204?source=rss-c8da7c5c84a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e9b7ddc204</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Milan Nosáľ]]></dc:creator>
            <pubDate>Tue, 25 Apr 2017 20:17:31 GMT</pubDate>
            <atom:updated>2017-04-25T20:17:31.884Z</atom:updated>
            <content:encoded><![CDATA[<p>So Swift Protocol-Oriented Programming (POP): a new paradigm overthrowing Object-Oriented Programming (OOP), or yet another hype? There are articles over the internet saying farewell to OOP and gladly welcoming POP — as an example take <a href="https://medium.com/ios-os-x-development/how-protocol-oriented-programming-in-swift-saved-my-day-75737a6af022">blog entry</a> from <a href="https://medium.com/@nikantvohra?source=post_header_lockup">NIkant Vohra</a>. This hype can be harmful to programming beginners — they might come to conclusion that they do not need the OO paradigm, and they will not learn about it nor from it. Why would this be a mistake? Read on.</p><p>In this article I explain why I believe POP is not a new programming paradigm overthrowing OOP, rather it is an <em>enhanced implementation flavour of OOP</em>. Now don’t get me wrong — I believe that using POP implementation in Swift is a great way to write <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">clean code</a>, and it is one of the best OOP implementations nowadays. But please, let us not jump into burying OOP yet.</p><p>Throughout the article I will use a simplified version of the code example from Hoffman’s Swift 3 Protocol-Oriented Programming <a href="https://www.packtpub.com/application-development/swift-3-protocol-oriented-programming-second-edition">[2]</a> — in the example I will assume that we want to implement different Vehicle types for a video game. More on it in next section.</p><h3>Protocol-Oriented Programming Summed Up</h3><p>POP promotes using protocols (<a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html">specifications of functionality requirements</a>) with structures implementing them over using class inheritance hierarchies for the purpose of code reuse and type categorisation. So, instead of implementing a superclass Vehicle with empty methods doLandAttack, doSeaAttack, and doAirAttack, you write 3 protocols, LandVehicle, SeaVehicle, and AirVehicle, each of which will specify requirement for a single respective method. Then, when you have an Amphibious vehicle, it will implement just LandVehicle and SeaVehicle protocols, and it will not get bloated by unwanted empty methods, such as doAirAttack in our simplified example.</p><p>Following is the superclass based counter-example. As you can see, Amphibious class inherits also unwanted doAirAttack method.</p><pre>class Vehicle {<br>  var vehicleName: String { return &quot;&quot; }<br>  func doLandAttack() { }<br>  func doAirAttack() { }<br>  func doSeaAttack() { }<br>}</pre><pre>class Amphibious : Vehicle {<br>  override var vehicleName: String {<br>    return &quot;Amphibious&quot;<br>  }</pre><pre>  override func doLandAttack() {<br>    print(&quot;Performing land attack&quot;)<br>  }</pre><pre>  override func doSeaAttack() {<br>    print(&quot;Performing sea attack&quot;)<br>  }<br>}</pre><p>Now the proposed POP solution looks as follows:</p><pre>protocol Vehicle {<br>  var vehicleName: String { get }<br>}</pre><pre>protocol LandVehicle: Vehicle {<br>  func doLandAttack()<br>}<br>extension LandVehicle {<br>  func doLandAttack() { print(&quot;Performing land attack&quot;) }<br>}</pre><pre>protocol SeaVehicle: Vehicle {<br>  func doSeaAttack()<br>}<br>extension SeaVehicle {<br>  func doSeaAttack() { print(&quot;Performing sea attack&quot;) }<br>}</pre><pre>protocol AirVehicle: Vehicle {<br>  func doAirAttack()<br>}<br>extension AirVehicle {<br>  func doAirAttack() { print(&quot;Performing air attack&quot;) }<br>}</pre><pre>struct Amphibious: LandVehicle, SeaVehicle {<br>  var vehicleName: String { return &quot;Amphibious&quot; }<br>}</pre><p>As you can see, now concrete implementations of the vehicles, Amphibious structure in this case, is much cleaner and nicer than in the previous one (the fact that the code is longer is not a problem, cleaner architecture is much more important).</p><h3>Protocol-Oriented Programming versus Object-Oriented Programming</h3><p>There are several claims about advantages of POP over OOP. Each subsection of this section will discuss one.</p><p>Before diving into the discussions, I would like to point out that I consider<em> </em><a href="http://www.artima.com/designtechniques/interfaces6.html"><em>the interface first approach</em></a><em> a fundamental approach to OO software development</em>. Using interfaces as types everywhere where possible allows better code separation and less interdependency between concrete implementations, which is fundamental to <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">clean code</a>. The fact that you are programming against an interface, and not any particular implementation, allows you to swap or mockup implementations very easily. I had to mention it, because in my world, when you say: “Write protocol/interface first, and only then write implementation,” it does not contradict OOP principles, rather nicely complements them. For me, writing interfaces/protocols first is “nothing more” than a very good practice to achieve clean code in OOP (which is of course a BIG deal — I just don’t consider it a new paradigm).</p><h4>1. Single inheritance language such as Swift can lead to bloated superclasses. Protocols allow smaller more concise units of features to be composed.</h4><p>Resources: <a href="https://developer.apple.com/videos/play/wwdc2015/408/">[1]</a>, <a href="https://www.packtpub.com/application-development/swift-3-protocol-oriented-programming-second-edition">[2]</a> (page 29), <a href="https://www.raywenderlich.com/148448/introducing-protocol-oriented-programming">[3]</a></p><p>True, a single inheritance OO language makes some of the situations complicated. But hold on just yet — this is not really such a destructive blow to OOP as it might seem on the first sight.</p><p>OOP was never restricted to single inheritance — this is a decision of most language authors due to some issues with the multiple inheritance, mainly around ambiguity, e.g., the <a href="https://en.wikipedia.org/wiki/Multiple_inheritance">Diamond Problem</a>. But <strong>this issue does</strong> <strong>concern Swift’s protocol extensions</strong> as well — what if you implement two protocols that provide default implementation for the same method, but you do not override it in you structure? Which implementation should be called? Swift deals with this using restrictive policy — it will not compile. See the following example — protocol Vehicle defines property vehicleName, there are two protocols implementing Vehicle, protocols LandVehicle and SeaVehicle, and they both provide default implementation of the vehicleName via extensions. Finally, struct Amphibious wants to implement both these protocols. But which of the default implementation should be used in Amphibious, the one from LandVehicle, or the one from SeaVehicle? Swift will not compile this and we will be forced to provide our implementation.</p><pre>protocol Vehicle {<br>  var vehicleName: String { get }<br>}</pre><pre>protocol LandVehicle: Vehicle {<br>  func doLandAttack()<br>}<br>extension LandVehicle {<br>  var vehicleName: String { return &quot;LandVehicle&quot; }<br>  func doLandAttack() {<br>    print(&quot;Performing land attack&quot;)<br>  }<br>}</pre><pre>protocol SeaVehicle: Vehicle {<br>  func doSeaAttack()<br>}<br>extension SeaVehicle {<br>  var vehicleName: String { return &quot;SeaVehicle&quot; }<br>  func doSeaAttack() {<br>    print(&quot;Performing sea attack&quot;)<br>  }<br>}</pre><pre>struct Amphibious: LandVehicle, SeaVehicle {<br>  // this won&#39;t compile due to ambiguity<br>}</pre><p>Basically, from this aspect we can consider <em>protocol extensions a specific implementation flavour of the multiple inheritance feature of OOP</em>.</p><h4>2. Classes supposedly do not allow us to express relationship between the type of self and the type of other.</h4><p>Resource: <a href="https://developer.apple.com/videos/play/wwdc2015/408/">[1]</a></p><p>Dave Abrahams <a href="https://developer.apple.com/videos/play/wwdc2015/408/">[1]</a> shows following code as a counter-example showing the superiority of protocols over classes:</p><pre>class Ordered {<br>  func precedes(other: Ordered) -&gt; Bool {<br>    fatalError(&quot;implement me!&quot;)<br>  }<br>}</pre><pre>class Number : Ordered {<br>  var value: Double = 0<br>  override func precedes(other: Ordered) -&gt; Bool {<br>    return value &lt; (other as! Number).value<br>  }<br>}</pre><p>In this example, he criticises two aspects of this code:</p><ul><li>Using fatalError call when we don’t want a default implementation.</li><li>Downcast in the subclass (as! Number) — in Ordered class we cannot define that other parameter has to be of the same subtype as the self.</li></ul><p>POP in Swift provides a cleaner and nicer solution:</p><pre>protocol Ordered {<br>  func precedes(other: Self) -&gt; Bool<br>}</pre><pre>struct Number : Ordered {<br>  var value: Double = 0<br>  func precedes(other: Number) -&gt; Bool {<br>    return self.value &lt; other.value<br>  }<br>}</pre><p>This is superior because:</p><ul><li>Ordered no longer has to contain ugly fatalError call.</li><li>Self type statically specifies that precedes can be applied only to subclasses of the same type — therefore a Number can be compared only to another Number, etc.</li><li>Moreover, thanks to Self type we no longer need to use downcast. In the Number structure we implement precedes method with the other argument of the Number type — no need to downcast anymore.</li></ul><p>There are two reasons why I have to consider this also just an OOP feature implementation:</p><ol><li>fatalError problem with the class version is artificial. No self-respecting OO programmer would use class to define Ordered type as above — we would use interface as a requirement specification (or protocol in Swift). <strong><em>We use interfaces for requirement specification, not classes</em></strong>. If we needed for some reason a class, in Java we can use abstract class. It was Swift authors’ decision not to support abstract classes. I am not claiming here that abstract classes are good — I trust Swift authors’ that they had good reasons not to support them, I am just pointing out that this particular problem seems to be specific for Swift implementation of OOP, and it cannot be generalised for the OOP principles.</li><li>Self keyword for better static type relationships is great — no argument here. However, how does this type system enhancement really changes the paradigm? I do not see why this type system behaviour could not be implemented in all OOP languages, and I believe it fits nicely with the OO design. I really like this enhancement, but I don’t think it is a paradigmatical change.</li></ol><h4>3. Implicit sharing of state due to reference passing that increases complexity of programs.</h4><p>Resource: <a href="https://developer.apple.com/videos/play/wwdc2015/408/">[1]</a></p><p>In OO languages, objects are by default passed around as reference. How does this implementation feature relate to definition of OOP — is passing by reference the requirement of OOP, or is it just an “implementation detail” of a particular OO language? I am not aware of any definition stating one or the other, I would expect that it is rather a traditionally accepted convention — objects are passed as references and considered an OOP implementation, and structures are passed as values and they are considered relicts from procedural programming (thus not part of OOP). Now traditionally, structures do not include behaviour, thus they are fitting the non-OOP conventional expectations. Swift, however, treats structures differently and allows behaviour defined on them. Basically, in Swift, <a href="http://stackoverflow.com/questions/24232799/why-choose-struct-over-class/24232845">structures</a> are classes passed as values, thus making them much closer to OOP paradigm. Considering this, can we still call Swift structures non-OOP? The only other difference left is that they do not support inheritance, however, should we allow that, Swift structures would perfectly fit the concept of a class in OOP.</p><p>Is this small difference a change in paradigm? If any of the claims about POP is a paradigmatical change, this is it. Inheritance is an integral part of the OOP. Shall we decide not to support it in a GPL (General Purpose Language), we cannot really claim the language to be OO. However, here come protocols and protocol extensions, which allow the structures to inherit default implementations of methods. While not full fledged inheritance, it comes really close to what we want inheritance for (because in some sense we can look at protocols with default implementations as a special very restricted case of an abstract class). This blurs the difference between OOP and POP. Although I tend to consider POP again just an implementation flavour of the OOP paradigm, in this case I will leave the decision upon the reader — the question here is rather philosophical.</p><p>Still, Dave Abrahams does have a point here. Implicit sharing of state imposes increased complexity on the programs, which in effect can cause bugs. Passing values prevents this, moreover it has some other advantages, e.g., thread safety. I must say that I definitely agree with Swift guideline to use structures everywhere where possible. In Swift, it is up to the programmer to decide whether to use value passing or reference passing in a given case. In my opinion, this choice should be allowed in all OO languages.</p><h4>4. Unlike multiple inheritance of classes which some programming languages support, protocol extensions do not introduce any additional state.</h4><p>Resource: <a href="https://www.raywenderlich.com/148448/introducing-protocol-oriented-programming">[3]</a></p><p>This claim elaborates on claim #1 — multiple inheritance versus protocol extensions. And again, <em>POP in this aspect is a simplification of the standard OOP technique of multiple inheritance</em>. The same effect can be achieved using superclasses in multiple inheritance, without using any stored properties. In principle, the “old” multiple inheritance of OOP is a more powerful case of protocol extensions in POP. It allows the same, and moreover, allows inheriting multiple states.</p><p>Yes, state in multiple superclasses increases code complexity, and therefore it is a good practice to avoid it. There is no argue in that. However, from my viewpoint, <strong><em>clean code in OOP would be very much like the clean code in POP</em></strong>. The only difference is that POP (or rather Swift, as the language implementation of protocol extensions) allows to use nicer syntactical features to achieve this goal, and sometimes forces us write it simpler and thus better (as in this case). Which, of course, is <em>awesome</em>.</p><h4>5. Protocols can be adopted by classes, structs and enums. Base classes and inheritance are restricted to class types.</h4><p>Resources: <a href="https://www.packtpub.com/application-development/swift-3-protocol-oriented-programming-second-edition">[2]</a> (page 29), <a href="https://www.raywenderlich.com/148448/introducing-protocol-oriented-programming">[3]</a></p><p>Swift structures and enums are surely neat. They allow us to write some pretty nice solutions for our everyday problems (e.g., take a look <a href="https://appventure.me/2015/10/17/advanced-practical-enum-examples/">here</a> at what you can do with Swift enums).</p><p>But again, my question here is: <em>How does this feature contradicts OO principles?</em> I already discussed Swift structures in claim #1. Does the same apply to Swift enums? I believe so. Instead of looking at this as creating a new paradigm, I would argue that <strong><em>Swift structures and enums are bringing traditional structures and enums closer to the OO paradigm!</em></strong> Indeed, by allowing enums to carry additional associated values, define their own methods and properties, implement protocols, we are just transforming enum constants closer to the shape of objects from OOP. I don’t think they are contradicting OO paradigm.</p><h3>Conclusion</h3><p>I will try to conclude this article very swiftly (pun intended). For me, <strong><em>POP is an implementation flavour of the OOP</em></strong> — it uses protocol extensions to deal with multiple inheritance, “objectified” structures with behaviour that are passed around as values to deal with implicit state sharing, etc. This implementation flavour is great, it allows the programmers to write the clean code easier. However, <strong><em>saying farewell to OOP in Swift is just another hype.</em></strong></p><p>Simply put: New paradigm? No! But is it great? Yes, indeed!</p><p>There is a lesson here for the Swift programmers: <strong>do </strong>learn structures, protocols and their extensions, <strong>do</strong> use them whenever possible and applicable, <strong>but</strong> <strong>do not </strong>forget object-oriented paradigm yet, because OO design advises you on how to design those structures, how to design those protocols. Moreover, conventional OO implementation in Swift (i.e., classes) can be very helpful if not necessary in many cases — sometimes you need reference passing, sometimes you need a superclass. Have an open mind, but put on it a firewall that will critically asses any new hype.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59e9b7ddc204" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>