Slide 1

Slide 1 text

S w i f t M e e t u p , H a m b u r g , S e p 1 7 t h 2 0 1 5 PROTOCOL-ORIENTED PROGRAMMING IN SWIFT Thilo Horstmann @thilo

Slide 2

Slide 2 text

OOP IS GREAT! WE ARE DOING THIS FOR YEARS … Classes are managing complexity We have Abstraction Access Control Namespace Encapsulation Polymorphism Extensibility / Inheritance 2

Slide 3

Slide 3 text

OOP IS GREAT! BUT WAIT … What about Ownership? - C++: You have to manage the memory - Automatic Memory Management (almost) fixed that Immutable Data / Shared Mutable State? - when do you have a consistent state of your object Rich Hickey: Are We There Yet?
 (http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey) 3 Data A B

Slide 4

Slide 4 text

OOP IS GREAT! BUT WAIT … What’s the value of x? 4 arr = [1, 2, 3] process(arr) arr[0] = arr[0] + 1

Slide 5

Slide 5 text

OOP IS GREAT! BUT WAIT … Complex class hierarchies - You inherit always everything from the superclass even if you don’t need it - how to test derived classes (perhaps including abstract superclasses) Forced Downcasts … - as! ASubclass, classes for abstraction - usually a “Type safety hole” Retroactive Modeling … - how to add functionality to already existing classes 5

Slide 6

Slide 6 text

WHAT CAN WE DO? Functional Languages try to avoid shared mutable state - Clojure, Haskell, Erlang, … - Building blocks are pure functions - Managing state e.g. via STM (software transactional memory) 6

Slide 7

Slide 7 text

PROTOCOL-ORIENTED PROGRAMMING IN SWIFT Value Types - “a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.” Protocols - “defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.” - “can be adopted by a class, structure, or enumeration” Extensions - “add new functionality to an existing class, structure, enumeration, or protocol type.” 7

Slide 8

Slide 8 text

DANGER ZONE: LIVE CODING! 8

Slide 9

Slide 9 text

ADVANTAGES OF PROTOCOL-ORIENTED PROGRAMMING - Supports value types (and classes) - Supports static type relationships (and dynamic dispatch) - Non-monolithic - Supports retroactive modeling - Doesn’t impose instance data on models - Doesn’t impose initialisation burdens on models - Makes clear what to implement (from WWDC 2015 talk) 9