DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

Protocol oriented Programming (PoP)

This post is a part of my blogpost series while learning Swift and Programming paradigms. First part on Functional Programming can be found here.

Protocol oriented programming (POP) can be said as as – a way to adhere the “ Program to interface not to implement ” principle – which is one of the basic design principles of software development. Structure your code such that you define interfaces first then make the classes implement it. Define interfaces using protocols and then make classes implement them. POP is just another technical term for the interface programming in Swift programming language.

Yes! There are additional advantages of POP in swift using “Extensions” along with protocols in Swift.

Let us discuss this with a classic example – Shapes and its classes.

Any shape has area. Every shape needs to be drawn on some canvas. Typically an average programmer thinks:

  • Let’s have a base class named Shape.
  • Let’s derive all other concrete classes from Shape class.

The first and foremost disadvantage of this solution is all concrete class inherits everything from base class whether its needed or not. Along with that multiple inheritance is not possible and moreover its a bad way.

In a practical world as the product grows its code grows and there will be a lot of overhead built over a period of time.

Here comes Protocol Oriented Programming – creating interfaces

This is link to Xcode playground @ github – giving a typical example of POP. Please go through the code before proceeding to understand the advantages.

Some plus points of POP :

  • No overhead of base class.
  • Protocol extensions are a great way to give default implementation.
  • Classes can conform to multiple protocols also use their default implementations without overhead of inheritance.
  • Restrict access ONLY to specific functionalities of an object.
  • Protocols can be conformed by structures & enumerations in Swift. Class-Only protocols can also be defined
[protocol TheClassOnlyProtocol: class { ... }]

.

  • Protocols can be used as a type for variables , which is more dynamic than declaring variables with concrete classes.
  • Delegation works as it used to in Objective-C.
  • Protocols can be used in Collection types
  • A Protocol can inherit from multiple other protocols ( multiple inheritance )

This is my understanding of POP. Please do share your comments below.

Hope you found this post useful to some extent.

Top comments (0)