in ,

Value-Oriented Programming, Hacker News

    

    

  

(August)   

At WWDC 2018, in a very influential session titled (Protocol-Oriented Programming in Swift

, Dave Abrahams explained how Swift’s protocols can be used to overcome some shortcomings of classes. He suggested this rule: “Don’t start with a class. Start with a protocol ”.

To illustrate the point, Dave described a protocol-oriented approach to a primitive drawing app. The example worked from a few of primitive shapes:

protocol Drawable {}

struct

  (Polygon)  :  
(Drawable)

{

  

var corners :
[CGPoint] =
}
struct
  Circle  :  
(Drawable)

{

  

var center :
(CGPoint)   
var radius :
(CGFloat)
}
struct
  Diagram  :  
(Drawable)

{

  

var elements
:
=
}

These are value types. That eliminates many of the problems of an object-oriented approach:

    Instances aren't shared implicitly

    The reference semantics of objects add complexity when passing objects around. Changing a property of an object in one place can affect other code that has access to that object. Concurrency requires locking, which adds tons of complexity.

      No problems from inheritance

      Reusing code via inheritance is fragile. Inheritance also couples interfaces to implementations, which makes reuse more difficult. This is its own topic, but even OO programmers will tell you to prefer “composition over inheritance”.

    No imprecise type relationships

    With subclasses, it's difficult to precisely identify types. e.g. with NSObject.isEqual () , you must be careful to only compare against compatible types. Protocols work with generics to precisely identify types.

    To handle the actual drawing, a Renderer protocol was added that describes the primitive drawing operations:

    protocol Renderer {    func move ( to p

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

China's 'Bat Woman' Shi Zhengli denies 'trying to defect with confidential files' – Daily Mail, Dailymail.co.uk

China's 'Bat Woman' Shi Zhengli denies 'trying to defect with confidential files' – Daily Mail, Dailymail.co.uk

UCF researchers develop groundbreaking new rocket-propulsion system, Hacker News

UCF researchers develop groundbreaking new rocket-propulsion system, Hacker News