Bobj-C
Bobj-C

Reputation: 5426

Protocol Oriented Programming

As we transition our brains from Object Oriented Programming to Protocol Oriented Programming how can I do the following ?

let's say I have a JSON object representing Model has {created_time,updated_time,type,...} and those values are common in 5 Model objects.

is it right to make a protocol contains all the above properties like the following

protocol xxx {
   var type : String { get }
   var updatedTime : String { get }
   var createdTime : String { get }
   //...//
}  

and then all the 5 structs conform to this protocol

Upvotes: 8

Views: 1083

Answers (2)

Qbyte
Qbyte

Reputation: 13263

Speaking of Protocol Oriented Programming Swift 2 has protocol extensions which allow default implementations. This also replaces many cases where you would use a superclass instead.

In this case:

// extension of your example protocol
extension xxx {
   var type : String { return "a type" }
   var updatedTime : String { return "00:00" }
   var createdTime : String { return "00:00" }
   //...//
}

// struct which conforms to it
struct Astruct: xxx {}

// using the properties
Astruct().type
Astruct().updatedTime

if all properties and methods have a default implementation by the protocol extension you don't have to provide any yourself. However you can "override" them only by implementing them.

So you're decision is right and you should use protocols as often as possible.

The only big drawback is that there is no super where you can explicitly call the default implementations. A workaround (see this answer) would require a superclass which makes the protocol almost redundant.

Upvotes: 1

ezig
ezig

Reputation: 1229

I would say that's a perfectly good solution. The alternative would be having a base class with those properties and have all five of those models inherit from the base class, but there's no particular reason to use inheritance here.

A protocol is just a "contract" that guarantees a class has certain properties or behavior. To me, your example here feels very "contractual."

By contrast, inheritance implies a "is-a" relationship (e.g. a Ford is-a car). To me, this feels more like a contract than an "is-a" case. Of course, neither choice is wrong, but think your protocol idea here is good.

Upvotes: 8

Related Questions