30

From Apple's own website: "At the heart of Swift's design are two incredibly powerful ideas: protocol-oriented programming and first class value semantics."

Can someone please elaborate what exactly is protocol oriented programming, and what added value does it bring?

I have read this and watched the Protocol-Oriented Programming in Swift video, but coming from an Objective-C background still haven't understood it. I kindly ask for a very plain English answer along with code snippets & technical details about how it's different from Objective-C.

Just one of the confusions I have is using <tableViewDelegate, CustomDelegate> Couldn't we also conform to multiple protocols in Objective-C as well? So again how is Swift new?


EDIT: See Protocol-Oriented Views video. I find this video to be more basic and easier to grasp a meaningful use case. The WWDC video itself is a bit advanced and requires more breadth. Additionally the answers here are somewhat abstract.

Honey
  • 24,125
  • 14
  • 123
  • 212
  • 1
    It is (almost) the same as [interfaced based programming](https://en.wikipedia.org/wiki/Interface-based_programming) in, say, Java. – Rudy Velthuis May 30 '16 at 16:42
  • @RudyVelthuis But I don't know Java! Would I still understand it easily? – Honey May 30 '16 at 16:47
  • 2
    Watch [Crusty](https://developer.apple.com/videos/play/wwdc2015/408/) – vadian May 30 '16 at 16:51
  • 2
    @vadian That's the exact same video he referenced in his question. But, that video is such an accessible introduction to the topic that I'm unclear how you can watch it and and have these sorts of questions. – Rob May 30 '16 at 17:28
  • @Rob I'll watch again...my major confusion is about the different meanings 'protocol' carries in the 2 languages and we already have some form of multiple protocol conformance in objc – Honey May 30 '16 at 17:32
  • 1
    @asma22 There is no difference in the meaning of "protocol". Swift just added new features to protocols (protocol extensions, protocol generics, etc.), but it's fundamentally still the same meaning of "protocol" as in ObjC. – Alexander Jun 02 '16 at 13:53
  • 5
    IMO this question and the answers are pretty useful. It's a shame when great questions get closed because they are deemed not to be a good fit for SO. – user1725145 Jun 04 '16 at 16:13
  • 1
    The video makes me sad at 8:50 when Professor Blowing Your Mind basically states that OOP is single inheritance. His arguments may be solid for single inheritance, but are much less compelling in the universe where OOP means more than one superclass. – iJames Apr 03 '18 at 18:18

5 Answers5

39

Preface: POP and OOP are not mutually exclusive. They're design paradigms that are greatly related.

The primary aspect of POP over OOP is that is prefers composition over inheritance. There are several benefits to this.

In large inheritance hierarchies, the ancestor classes tend to contain most of the (generalized) functionality, with the leaf subclasses making only minimal contributions. The issue here is that the ancestor classes end up doing a lot of things. For example, a Car drives, stores cargo, seats passengers, plays music, etc. These are many functionalities that are each quite distinct, but they all get indivisibly lumped into the Car class. Descendants of Car, such as Ferrari, Toyota, BMW, etc. all make minimal modifications to this base class.

The consequence of this is that there is reduced code reuse. My BoomBox also plays music, but it's not a car. Inheriting the music-playing functionality from Car isn't possible.

What Swift encourages instead is that these large monolithic classes be broken down into a composition of smaller components. These components can then be more easily reused. Both Car and BoomBox can use MusicPlayer.

Swift offers multiple features to achieve this, but the most important by far are protocol extensions. They allow implementation of a protocol to exist separate of its implementing class, so that many classes may simply implement this protocol and instantly gain its functionality.

Alexander
  • 48,074
  • 8
  • 78
  • 121
  • 1: In objc...every protocol is to be applied onto its delegate. Like you say this protocol's name is – Honey May 30 '16 at 17:05
  • The naming has simply changed for some core types. The Foundation Frameworks's (`NS*` / `UI*`) protocols tend to keep their naming as it used to be. The delegate pattern still exists. – Alexander May 30 '16 at 17:22
  • Isn't composition only a matter of how you write your code? See this http://stackoverflow.com/questions/4192203/objective-c-multiple-inheritance – Honey May 30 '16 at 20:03
  • @asma22 "only a matter of how you write your code" Yeah, so? OOP is just "a matter a how you write your code". As is POP. – Alexander Jun 01 '16 at 15:37
  • My point is, if it's something that could have already been done in Objective-C before, then what's all the fuss about it in Swift? Meaning your answer doesn't really highlight the *differences* as per the link above. Kindly, can you explain the extensions part and what you mean by default implementation. Please explain in Plain English as much as possible – Honey Jun 01 '16 at 20:37
  • 1
    @asma22 just because it was possible, doesn't mean it was the prevailing convention. The designers of Swift used the opportunity of developing a new language to rethink the kinds of design patterns they want to embrace. For more on protocol extensions read https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID521 – Alexander Jun 02 '16 at 13:51
  • 2
    I suggest you give a read through the entire language guide. It's very well written and will answer many of these sorts of questions far better than I could – Alexander Jun 02 '16 at 13:52
  • Thanks for getting back to me. Fair enough I will, ASAIK I messed up to design patterns: Delegation pattern and Adapter pattern since both were using `protocol`s to do their work and I was mostly using the delegation side of it in tableViews, CollectionViews, etc. Please correct me if I am wrong about adapter vs. delegation. **P.S.** I am not saying this a beautiful question, but this is a question that when I ask my peers on the *same level*, we all get confused and not that it counts but 3 people favorited it :] – Honey Jun 02 '16 at 14:29
  • 1) I removed the itemized questions so kindly if you can update accordingly. 2) I would appreciate if you can add some laymen explanation for defaulting and its technical benefits as you have done for 'composition over inheritance' . Or possibly something I haven't mentioned... – Honey Jul 14 '16 at 19:38
  • @Honey `I would appreciate if you can add some laymen explanation for defaulting and its technical benefits` Of POP over OOP? Inheritance is the defining trait of OOP. POP avoids this, and uses POP instead. There's not much more to it. – Alexander Jul 14 '16 at 19:43
  • 1
    @Alexander I'd argue that the framing of OOP above is focused on single inheritance. With multiple inheritance, mixins and functionalities can be very small and lead to comfortably sized testable leaf subclasses without the imposition of always implementing full interfaces. It seems like POP and OOP from this perspective can go hand in hand smoothly. – iJames Apr 03 '18 at 17:54
  • @iJames This is true, but multiple inheritance is quite rare. C++ is the only big player in this space. Python technically has multiple inheritance, but it's usually avoided – Alexander Apr 03 '18 at 18:11
  • @Alexander Python is avoided or multiple inheritance is avoided? :-) I suppose if we're going to say OOP is generally single inheritance, we need to reclassify multiple inheritance languages in a new category. I don't have the personal experience developing fully tested multiple inheritance to say it's a fine alternative, but at face value, it knocks down the main argument of against single inheritance, the problem of massive base classes. So it's important to be clear that (MIB)OOP hasn't been shot down as severely (though it still could be if somebody wanted to try.) – iJames Apr 04 '18 at 23:46
17

It surprised me that none of the answers mentioned value type in POP.

To understand what is protocol oriented programming, you need to understand what are drawbacks of objected oriented programming.

  1. It (Objc) has only one inheritance. If we have very complicated hierarchy of inheritance, the bottom class may have a lot of unnecessary state to hold.
  2. It uses class which is a reference type. Reference type may cause code unsafe. e.g. Processing collection of reference types while they are being modified.

While in protocol oriented programming in swift:

  1. It can conform multiple protocols.
  2. It can be used by not only class, but also structures and enumerations.
  3. It has protocol extension which gives us common functionality to all types that conforms to a protocol.
  4. It prefers to use value type instead of reference type. Have a look at the standard swift library here, you can find majority of types are structures which is value type. But this doesn't mean you don't use class at all, in some situation, you have to use class.

So protocol oriented programming is nothing but just an another programming paradigm that try to solve the OOP drawbacks.

brianLikeApple
  • 3,803
  • 1
  • 23
  • 44
  • 3
    1. OOP can be done with multiple inheritance, as C++ does, 2. Structures exist to facilitate POP, so their lack of OOP isn't relevant. Enums could be implemented by classes too. 3. Protocol extensions / mixins are possible in OOP. – Alexander Nov 03 '16 at 00:20
  • 2
    @AlexanderMomchliov 1. Yes, agree, but some popular language cannot have multiple inheritance like c#, Java etc. It is Apple thing so I mainly differ it from Objc 2. From the video of Protocol-Oriented Programming in Swift, it clearly demonstrates why Apple prefer type value not reference value. So Structure or Enums conform protocol is reasonable and many language cannot do that. 3. Protocol extension is not just extension but you can also give a default implementation of method without using inheritance to reduce the duplicated code. Let me know if I am not correct. – brianLikeApple Nov 03 '16 at 09:43
9

In Objective C protocol is the same thing as interface in most languages. So in Objective C protocol's usage is limited to SOLID principle "Depend upon Abstractions. Do not depend upon concretions."

In Swift protocols were improved so seriously that since they still could be used as interfaces in fact they are closer to classes (like Abstract classes in C++)

In Objective C the only way to share functionality between classes is an inheritance. And you could inherit the only one parent class. In Swift you could also adopt as many protocols as you want. And since protocols in Swift can have default methods implementation they give us a fully-functional Multiple inheritance. More flexibility, better code reuse - awesome!

Conclusion:

Protocol Oriented Programming is mostly the same as OOP but it pays additional attention to functionality sharing not only via inheritance but also via protocol adoption (Composition over inheritance).

Worth to mention that in C++ abstract classes are very similar to protocols in Swift but no one says C++ supports some specific type of OOP. So in general POP is a one of the versions of OOP if we speak about programming paradigms. For Swift POP is an improved version of OOP.

Avt
  • 16,037
  • 4
  • 48
  • 67
  • I understand some parts of what you are saying. And thanks for the wikipedia link. It's great. So you are saying the word protocol doesn't have similar meaning in the 2 languages? For Objective-C isn't that we can also make our viewcontroller class conform to multiple protocols? Extending its functionality? I don't understand the difference. Kindly can you elaborate more – Honey May 30 '16 at 17:25
  • 1
    I think you have got the main idea. In Objective C protocol is the same thing as `interface` in most languages. In Swift protocols were improved so seriously that since they still could be used as interfaces in fact they are closer to classes (like `Abstract classes` in C++). – Avt May 30 '16 at 19:36
  • Can you please vote for re-opening the question? I believe the ambiguity is removed now – Honey Jun 04 '16 at 22:32
5

Adding to the above answer

Protocol is a interface in which signature of methods and properties are declared and any class/struct/enum subclassing the enum must have to obey the contract means they have to implement all the methods and properties declared in superclass protocol.

Reason to use Protocol

Classes provide single inheritance and struct doesn't support inheritance. Thus protocols was introduced.

Extension The methods declare inside the protocol can be implemented inside the extension to avoid the redundancy of the code in case protocol is being inherited in multiple class / struct having same method implementation. We can call the method by simply declaring the object of struct/enums. Even we can restrict the extension to a list of classes, only restricted class will be able to use the method implemented inside the extension while rest of the classes have to implement method inside own class.

Example

protocol validator{

    var id : String{ get }
    func capitialise()-> (String)

}

extension validator where Self : test{
    func capitialise() -> String{
        return id.capitalized
    }
}

class test : validator {

    var id: String

    init(name:String) {
        id = name
    }
}

let t = test(name: "Ankit")
t.capitialise()

When to use In OOP suppose we have a vehicle base class which is inherited by the airplane, bike, car etc. Here break, acceleration may be common method among three subclass but not the flyable method of airplane. Thus if we are declaring flyable method also in OOP, the bike and car subclass also have the inherit flyable method which is of no use for those class. Thus in the POP we can declare two protocols one is for flyable objects and other is for break and acceleration methods. And flyable protocol can be restricted to use by only the airplane

Simon
  • 24,010
  • 36
  • 139
  • 249
garg
  • 2,344
  • 20
  • 20
0

Protocol Oriented Programming (POP)

  • Came since Swift 2.0
  • class (OOP)
    • is reference type
    • memory leak, incorrect data stored,race condition to access in complex multi-thread environments
    • can be large by inheriting members of super classes at chain time
  • struct (POP)
    • is value type - each time a fresh copy is made when needed
    • provides multi inheritance - inherits protocols
    • Protocol :
    • Defines what Methods, Properties and Initializes are required o Can inherit another Protocol(s)
    • Don’t have to use override keyword to implement protocol functions
  • Extensions:
    • Default value and The default implementation for protocol
    • Can add extra members to protocol
ItSNeverLate
  • 81
  • 2
  • 4