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

Type Driven Development — Валерий Попов (Yandex)

AvitoTech
December 02, 2017

Type Driven Development — Валерий Попов (Yandex)

В докладе Валерий рассматривает строгую типизацию, которая может стать еще одним рубежом обороны надежного приложения от ошибок разработчика. На примерах будет показано, как дополнительная информация, переданная на этапе компиляции, поможет отловить ряд ошибок, не доводя систему до падения в runtime. Расскажет, что мобильный разработчик может почерпнуть из языков, которые ставят типы во главе процесса разработки.

Avito iOS Winter Edition
02/12/2017

AvitoTech

December 02, 2017
Tweet

More Decks by AvitoTech

Other Decks in Technology

Transcript

  1. TESTS TESTS TESTS ESTS TEST TESTS TESTS TESTS ESTS TEST

    TESTS TESTS TESTS ESTS TEST TESTS TESTS TESTS ESTS TEST TESTS TESTS TESTS ESTS TEST TESTS TESTS TESTS ESTS TEST
  2. Practical › Type systems › Using types
 Agenda Theoretical ›

    Dependent types in Swift › Type DD approach

  3. Python: weak, dynamic 13 def binary_search(l, value): low = 0

    high = len(l)-1 while low <= high: mid = (low+high) if l[mid] > value: high = mid-1 elif l[mid] < value: low = mid+1 else: return mid return -1
  4. Swift: static, strong 16 func binarySearch<T: Comparable>(xs: [T], x: T)

    -> Int? { var recurse: ((Int, Int) -> Int?)! recurse = {(low, high) in switch (low + high) / 2 { case _ where high < low: return nil case let mid where xs[mid] > x: return recurse(low, mid - 1) case let mid where xs[mid] < x: return recurse(mid + 1, high) case let mid: return mid }} return recurse(0, xs.count - 1) }
  5. Money transfer 20 struct FailedTransaction { let isRejected: Bool let

    isCancelled: Bool let notEnoughMoney: Amount? }
  6. 21 struct FailedTransaction { let isRejected: Bool let isCancelled: Bool

    let notEnoughMoney: Amount? } let transaction = FailedTransaction ( isRejected: true, isCancelled: true, notEnoughMoney: nil )
  7. Product type 22 struct FailedTransaction { let isRejected: Bool let

    isCancelled: Bool let notEnoughMoney: Amount? }
  8. 27 func send(message: Message) throws { if message.isEncrypted { print(message.text)

    } else { throw MessageError.unsecured } } struct Message { let text: String var isEncrypted: Bool }
  9. 28 func send(message: Message) throws { if message.isEncrypted { print(message.text)

    } else { throw MessageError.unsecured } } let message = Message(text: "Hi!", isEncrypted: false) send(message: message)
  10. Compile time? 31 struct Message<T> { let text: String }

    enum Encrypted {} enum PlainText {}
  11. 32 func send(message: Message<Encrypted>) { print(message.text) } struct Message<T> {

    let text: String } enum Encrypted {} enum PlainText {}
  12. 33 func send(message: Message<Encrypted>) { print(message.text) } let message =

    Message<PlainText>(text: “Hi!”) send(message: message)
  13. 40 typedef void (^Compl)(NSData,NSError*) 
 - (void)performTask:(Compl)completion{ … completion(nil, nil)

    // ??? } typedef void (^Compl)(NSData,NSError*) 
 - (void)performTask:(Compl)completion{ … completion(data, error) // ??? }
  14. 44 func contentsOfFile( path: String) -> Result<String> { return .success("")

    } func performTask() -> Result<Void> { return .failure(Err.some) } enum Result<T> { case success(T) case failure(Error) }
  15. Dependent types 49 insSort : Vect n elem -> Vect

    n elem FUNC NAME ARGUMENT TYPE DEPENDENT TYPE ARGUMENT NAME RETURN TYPE
  16. 1 ≠ 2 51 protocol Nat { init() } struct

    Zero: Nat {} protocol NonZero: Nat { associatedtype Predecessor: Nat }
  17. 52 protocol NonZero: Nat { associatedtype Predecessor: Nat } struct

    Successor<N: Nat>: NonZero { typealias Predecessor = N } typealias One = Successor<Zero> typealias Two = Successor<One> typealias Three = Successor<Two> …
  18. 53 protocol BinaryOperation { associatedtype A: Nat associatedtype B: Nat

    } struct Successor<N: Nat>: NonZero { typealias Predecessor = N }
  19. 54 struct EQ {} extension BinaryOperation where A == B

    { var r: EQ { return EQ() } } struct NEQ {} extension BinaryOperation { var r: NEQ { return NEQ() } }
  20. 55 struct Compare <L: Nat, R: Nat>: BinaryOperation { typealias

    A = L typealias B = R } Compare<One, One>().r //EQ Compare<One, Two>().r //NEQ
  21. 56 //struct NEQ {} //extension BinaryOperation { // var r:

    NEQ { return NEQ() } //} Compare<One, Two>().r //Compile time error
  22. Type Holes in Swift 68 func typeHole<T> (_ description: String

    = "") -> T { fatalError("unfilled hole \(description)") }
  23. › Types and type systems › Painless types › Swift

    type system is almost good › Type DD Summary