Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Protocol-Oriented Programming in Swift

Protocol-Oriented Programming in Swift

These are the slides for the Swift Meetup "Protocol-Oriented Programming in Swift" in Hamburg, Sep 17th, 2015: http://www.meetup.com/Swift-Meetup-Hamburg/events/224604913/
The Xcode 7 Playground of the Live Coding session can be found here:
https://gist.github.com/thilo11/b8a0cf19f0afd2e113b7

Thilo Horstmann

September 17, 2015
Tweet

More Decks by Thilo Horstmann

Other Decks in Programming

Transcript

  1. 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
  2. OOP IS GREAT! WE ARE DOING THIS FOR YEARS …

    Classes are managing complexity We have Abstraction Access Control Namespace Encapsulation Polymorphism Extensibility / Inheritance 2
  3. 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
  4. OOP IS GREAT! BUT WAIT … What’s the value of

    x? 4 arr = [1, 2, 3] process(arr) arr[0] = arr[0] + 1
  5. 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
  6. 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
  7. 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
  8. 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