What is Protocol Oriented Programming

Protocol Oriented Programming : As a programmer or developer I can say that , neither I m completely understand the structured programming or Procedural programming or now protocol programming.Only thing I know that solving a problem using most suitable way ( suitable way means low resource and best performance ).

Lets coming to the topic , what exactly protocol oriented programming , let’s see

Protocol Oriented Programming is a new approach for programming which you decorate your classes, structs or enums using protocols. Swift does not support multiple inheritance, therefore problem pops out when you want to add multiple abilities to your class.Protocol Oriented Programming lets you to add abilities to a class or struct or enum with protocols which supports multiple implementations.

IMG 5408

I create a Protocol CAR below , Remember I created Protocol not CLASS

protocol Car {
var name: String { get }
var canRun: Bool { get }
var canJump: Bool { get }
}

Then I created two more protocols Runable and Jumpable

protocol Runable {
var roadLength: Int { get }
}
protocol Jumpable {
var weight: Double { get }
var steel: String { get }
}

Then I created abilities using our Protocol CAR,Runable,Jumpable

struct LongTruck: Car, Jumpable {
let name: String
let steel: String
let weight = 500.2
let canRun = false
let canJump = true
}
// LongTruck is a car with ability to Jump.

struct PickUpTruck: Car, Runable {
let name = "PickUP"
let roadLeagth = 30
let canRun = true
let canJump = false
}

As you see the above we used struct using Protocol we defined.
But there is a issue occurred while implementing this canJump and canRun are two abilities are custom structs. We fixed this issue but in a different manner.

We fixed this by Protocol Extension

extension Car {
var canRun: Bool { return self is Runable }
var canJump: Bool { return self is Jumpable }
}

Let try some example with code

let Longtruck = LongTruck(name: "trailer", steel: "Valyrian")
Longtruck. canRun // true
Longtruck. canJump // false
Longtruck.name

let pickuptruck = PickUpTruck()
pickuptruck. canJump // true
pickuptruck. canRun // false
// I wanted to add maxDistance feature.
protocol BigTruck: Runable {
var maxDistance: Double { get }
}
// Then I create brand new Car, DoubleTruck
struct DoubleTruck: Car, BigTruck {
let name = "BIGTruck01"
let RoadLength = 1000
let maxDistance = 1000 // in km
}

// So this extensibility made my code base more flexible. Consider, // I do not want maxDistance in Runnable but DoubleTruck.


Discover more from CODE t!ps

Subscribe to get the latest posts sent to your email.

Scroll to Top

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading