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

Building Robust Software (Episode 1)

Building Robust Software (Episode 1)

Presented at https://www.meetkt.org on 22 July 2021

Most of us can build software that works. But, building robust software that can withstand the test of time requires a shift in both mindset and skillset. Often, we have trouble finding out where to start.

This talk aims to shed some light on making that shift in both mindset and skillset. We'll begin by drawing some inspiration from the philosophy behind TCP and venture into functional programming principles to adopt ideas that can help us build expressive and robust programs.

We'll also look into an example for each idea and see how you can adopt it and implement it at work the very next day. We will leverage Kotlin's multi-paradigm abilities and its type system to bring most of these ideas to fruition.

Ragunath Jawahar

July 22, 2021
Tweet

More Decks by Ragunath Jawahar

Other Decks in Programming

Transcript

  1. Ragunath Jawahar • @ragunathjawahar
    Building Robust Software
    Episode 1 Small ideas, big impact

    View full-size slide

  2. Write code that communicates well.

    View full-size slide

  3. Example 1


    API Call / External Systems

    View full-size slide

  4. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  5. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  6. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  7. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  8. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  9. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  10. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  11. Response?
    • Successfully creates a user account and returns a Response 🎉

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View full-size slide

  12. Response?
    • Successfully creates a user account and returns a Response 🎉

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View full-size slide

  13. Response?
    • Successfully creates a user account and returns a Response 🎉

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View full-size slide

  14. Response?
    • Successfully creates a user account and returns a Response 🎉

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View full-size slide

  15. Response?
    • Successfully creates a user account and returns a Response 🎉

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View full-size slide

  16. 😊 😕 😨
    Caller’s emotions

    View full-size slide

  17. 😊 😕 😨
    Caller’s emotions

    View full-size slide

  18. 😊 😕 😨
    Caller’s emotions

    View full-size slide

  19. 😊 😕 😨
    Caller’s emotions

    View full-size slide

  20. Be conservative in what you send,
    be liberal in what you accept
    Robustness Principle

    View full-size slide

  21. Be conservative in what you send,
    be liberal in what you accept
    Robustness Principle

    View full-size slide

  22. Robustness Principle
    Be conservative in what you send,
    be liberal in what you accept

    View full-size slide

  23. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  24. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  25. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  26. interface AccountsApi {


    fun signup(email: String, password: String): Response?


    }
    AccountsApi.kt

    View full-size slide

  27. interface AccountsApi {


    fun signup(email: String, password: String): SignupResponse


    }
    AccountsApi.kt

    View full-size slide

  28. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  29. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  30. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  31. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  32. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  33. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  34. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  35. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View full-size slide

  36. Sealed Classes
    Sealed classes are used for representing restricted class hierarchies,
    when a value can have one of the types from a limited set, but cannot
    have any other type.

    View full-size slide

  37. Sealed Classes
    Sealed classes are used for representing restricted class hierarchies,
    when a value can have one of the types from a limited set, but cannot
    have any other type.

    View full-size slide

  38. Sealed Classes
    Sealed classes are used for representing restricted class hierarchies,
    when a value can have one of the types from a limited set, but cannot
    have any other type.

    View full-size slide

  39. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  40. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  41. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  42. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  43. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  44. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  45. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  46. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  47. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  48. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  49. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  50. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  51. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  52. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  53. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  54. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  55. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  56. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  57. Enforcing exhaustive when statements

    https://github.com/cashapp/exhaustive (compiler plugin)

    https://youtrack.jetbrains.com/issue/KT-12380 (Kotlin language proposal)

    View full-size slide

  58. Usage - Sealed Class Exhaustiveness
    val response = accountsApi.signup("John Doe", "[email protected]")


    when (response) {


    is AccountCreated
    ->
    saveUserId(response.userId)


    is EmailAlreadyRegistered
    ->
    showEmailAlreadyRegistered(response.registrationEmail)


    is InputValidationFailed
    ->
    showValidationErrors(response.errors)


    ConnectionError
    ->
    showCheckConnectionMessage()


    is ServerError, is UnknownError
    ->
    showTryAgainInSometimeMessage()


    }.exhaustive()

    View full-size slide

  59. 😊 😌
    Caller’s emotions

    View full-size slide

  60. 😊 😌
    Caller’s emotions

    View full-size slide

  61. 😊 😌
    Caller’s emotions

    View full-size slide

  62. What have we achieved?
    • Certainty

    • Convey business ideas in code

    • Improved readability

    • Represent errors as data

    View full-size slide

  63. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View full-size slide

  64. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View full-size slide

  65. Total Functions
    Total functions are functions that give you a valid return value for every
    combination of valid arguments.

    View full-size slide

  66. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  67. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  68. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  69. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  70. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  71. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  72. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  73. Partial Functions
    A partial function is a function that is not defined for all possible input
    values; in some cases returns a value, it may never return at all, throw
    an exception or simply crash a system.

    View full-size slide

  74. //
    Partial function


    fun signup(email: String, password: String): Response?


    //
    Total function


    fun signup(email: String, password: String): SignupResponse
    Partial vs. Total Functions

    View full-size slide

  75. //
    Partial function


    fun signup(email: String, password: String): Response?


    //
    Total function


    fun signup(email: String, password: String): SignupResponse
    Partial vs. Total Functions

    View full-size slide

  76. //
    Partial function


    fun signup(email: String, password: String): Response?


    //
    Total function


    fun signup(email: String, password: String): SignupResponse
    Partial vs. Total Functions

    View full-size slide

  77. //
    Partial function


    fun signup(email: String, password: String): Response?


    //
    Total function


    fun signup(email: String, password: String): SignupResponse
    Partial vs. Total Functions

    View full-size slide

  78. //
    Partial function


    fun signup(email: String, password: String): Response?


    //
    Total function


    fun signup(email: String, password: String): SignupResponse
    Partial vs. Total Functions

    View full-size slide

  79. //
    Partial function


    fun signup(email: String, password: String): Response?


    //
    Total function


    fun signup(email: String, password: String): SignupResponse
    Partial vs. Total Functions

    View full-size slide

  80. //
    Partial function


    fun signup(email: String, password: String): Response?


    //
    Total function


    fun signup(email: String, password: String): SignupResponse
    Partial vs. Total Functions

    View full-size slide

  81. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View full-size slide

  82. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View full-size slide

  83. Algebraic Data Types
    An algebraic data type is a kind of composite type, i.e., a type formed
    by combining other types.

    View full-size slide

  84. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  85. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  86. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  87. SignupResponse.kt
    sealed class SignupResponse {


    data class AccountCreated(val userId: String) : SignupResponse()


    data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse()


    data class InputValidationFailed(val errors: List) : SignupResponse()


    object ConnectionError : SignupResponse()


    data class ServerError(val statusCode: Int) : SignupResponse()


    data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse()


    }

    View full-size slide

  88. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View full-size slide

  89. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View full-size slide

  90. Where to apply?
    • Use it heavily on integration points with external systems (code that lives
    outside your own application)

    • Anti-corruption layers (both internal and external)

    • Take failure frequency and domain context into account (databases and
    fi
    le
    systems may not be good candidates. Network layer is a good starting point.)

    View full-size slide

  91. Example 2


    Division / Exceptions

    View full-size slide

  92. fun divide(dividend: Int, divisor: Int): Int {


    return dividend / divisor


    }
    Arithmetic.kt

    View full-size slide

  93. fun divide(dividend: Int, divisor: Int): Int {


    return dividend / divisor


    }
    Arithmetic.kt

    View full-size slide

  94. fun divide(dividend: Int, divisor: Int): Int {


    return dividend / divisor


    }
    Arithmetic.kt

    View full-size slide

  95. fun divide(dividend: Int, divisor: Int): Int {


    return dividend / divisor


    }
    Arithmetic.kt

    View full-size slide

  96. fun divide(dividend: Int, divisor: Int): Int {


    return dividend / divisor


    }
    Arithmetic.kt

    View full-size slide

  97. fun divide(dividend: Int, divisor: Int): Int {


    return dividend / divisor


    }
    Arithmetic.kt

    View full-size slide

  98. fun divide(dividend: Int, divisor: Int): Int {


    return dividend / divisor


    }
    Arithmetic.kt

    View full-size slide

  99. Exception in thread "main" java.lang.ArithmeticException: / by zero


    at org.example.ArithmeticKt.divide(Arithmetic.kt:3)


    at org.example.ArithmeticKt.main(Arithmetic.kt:7)


    at org.example.ArithmeticKt.main(Arithmetic.kt)

    View full-size slide

  100. Be conservative in what you send,
    be liberal in what you accept

    View full-size slide

  101. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  102. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  103. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  104. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  105. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  106. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  107. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  108. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  109. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  110. fun divide(dividend: Int, divisor: Int): Quotient {


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View full-size slide

  111. sealed class Quotient {


    object Infinity : Quotient()


    data class Result(val value: Double) : Quotient()


    }
    Quotient.kt

    View full-size slide

  112. sealed class Quotient {


    object Infinity : Quotient()


    data class Result(val value: Double) : Quotient()


    }
    Quotient.kt

    View full-size slide

  113. sealed class Quotient {


    object Infinity : Quotient()


    data class Result(val value: Double) : Quotient()


    }
    Quotient.kt

    View full-size slide

  114. sealed class Quotient {


    object Infinity : Quotient()


    data class Result(val value: Double) : Quotient()


    }
    Quotient.kt

    View full-size slide

  115. sealed class Quotient {


    object Infinity : Quotient()


    data class Result(val value: Double) : Quotient()


    }
    Quotient.kt

    View full-size slide

  116. Implications
    • Places burden on the consumer to handle both Infinity and
    Result types

    • The consumer may pass the Quotient type downstream. If that
    happens, downstream consumers should also deal with the added
    complexity

    View full-size slide

  117. Be conservative in what you send,
    be liberal in what you accept

    View full-size slide

  118. Be conservative in what you send,
    be liberal in what you accept
    conservative

    View full-size slide

  119. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  120. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  121. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  122. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  123. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  124. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  125. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  126. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  127. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  128. fun divide(dividend: Int, divisor: Integer.NonZero): Int {


    return dividend / divisor.number


    }
    Arithmetic.kt

    View full-size slide

  129. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  130. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  131. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  132. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  133. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  134. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  135. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  136. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  137. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  138. sealed class Integer {


    object Zero : Integer()


    data class NonZero(val number: Int) : Integer()


    companion object {


    fun from(number: Int): Integer = if (number
    ==
    0) {


    Zero


    } else {


    NonZero(number)


    }


    }


    }
    Integer.kt

    View full-size slide

  139. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  140. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  141. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  142. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  143. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  144. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  145. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  146. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  147. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  148. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  149. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  150. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  151. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  152. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  153. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  154. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  155. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  156. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  157. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  158. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  159. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  160. //
    Liberal inputs, conservative output (original)


    fun divide(dividend: Int, divisor: Int): Quotient


    //
    Conservative inputs, conservative output (tweaked)


    fun divide(dividend: Int, divisor: Integer.NonZero): Int
    Original vs. Tweaked

    View full-size slide

  161. What have we learnt?
    • Robustness principle (tweaked)

    View full-size slide

  162. Where to apply?
    • All layers and components that are within your system boundary

    View full-size slide

  163. Example 3


    File / Defensive Programming

    View full-size slide

  164. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  165. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  166. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  167. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  168. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  169. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  170. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  171. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  172. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  173. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  174. fun countFiles(directory: File, extension: String): Int {


    if (!directory.exists()
    ||
    !directory.isDirectory) {


    return 0


    }


    return directory


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  175. Be conservative in what you send,
    be liberal in what you accept
    conservative

    View full-size slide

  176. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  177. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  178. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  179. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  180. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  181. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  182. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  183. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  184. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  185. fun countFiles(directory: Directory.Valid, extension: String): Int {


    return directory


    .location


    .listFiles()


    ?.
    filter { it.name.endsWith(".$extension") }


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View full-size slide

  186. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  187. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  188. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  189. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  190. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  191. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  192. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  193. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  194. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  195. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  196. sealed class Directory {


    data class Valid(val location: File) : Directory()


    data class Invalid(val rawPath: String) : Directory()


    companion object {


    fun from(rawPath: String): Directory {


    val possibleDirectory = File(rawPath)


    val isDirectory = possibleDirectory.exists()
    &
    &
    possibleDirectory.isDirectory


    return if (isDirectory) {


    Valid(File(rawPath))


    } else {


    Invalid(rawPath)


    }


    }


    }


    }
    Directory.kt

    View full-size slide

  197. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  198. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  199. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  200. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  201. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  202. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  203. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  204. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  205. val directory = Directory.from("~/Documents/Finance")


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View full-size slide

  206. What have we learnt?
    • Protecting users of a type from making unnecessary defensive checks

    View full-size slide

  207. Where to apply?
    • All layers and components that are within your system boundary

    View full-size slide

  208. Example 4


    Username / Primitive Obsession

    View full-size slide

  209. /
    /
    Failing fast…

    View full-size slide

  210. View Presenter Model
    Model - View - Presenter

    View full-size slide

  211. View Presenter Model
    Model - View - Presenter

    View full-size slide

  212. View Presenter Model
    Model - View - Presenter

    View full-size slide

  213. View Presenter Model
    Model - View - Presenter

    View full-size slide

  214. View Presenter Model
    Model - View - Presenter

    View full-size slide

  215. View Presenter Model
    Model - View - Presenter

    View full-size slide

  216. View Presenter Model
    Model - View - Presenter

    View full-size slide

  217. View Presenter Model
    Model - View - Presenter

    View full-size slide

  218. View Presenter Model
    Model - View - Presenter

    View full-size slide

  219. View Presenter Model
    Model - View - Presenter

    View full-size slide

  220. View Presenter Model
    Model - View - Presenter

    View full-size slide

  221. Failure 1 username: String
    View Presenter Model
    username username
    failure
    failure

    View full-size slide

  222. Failure 1 username: String
    View Presenter Model
    username username
    failure
    failure

    View full-size slide

  223. Failure 1 username: String
    View Presenter Model
    username username
    failure
    failure

    View full-size slide

  224. Failure 1 username: String
    View Presenter Model
    username username
    failure
    failure

    View full-size slide

  225. Failure 1 username: String
    View Presenter Model
    username username
    failure
    failure

    View full-size slide

  226. Failure 1 username: String
    View Presenter Model
    username username
    failure
    failure

    View full-size slide

  227. Failure 1 username: String
    View Presenter Model
    username username
    failure
    failure

    View full-size slide

  228. Data Behavior

    View full-size slide

  229. Data Behavior

    View full-size slide

  230. Data Behavior

    View full-size slide

  231. Data Behavior

    View full-size slide

  232. Data Behavior

    View full-size slide

  233. sealed class Username {


    data class Valid(val text: String) : Username()


    data class Invalid(val reasons: Set) : Username()


    companion object {


    fun from(possiblyUsername: String): Username {


    possiblyUsername.find { !it.isLetter() }
    ?:
    return Valid(possiblyUsername)


    return Invalid(setOf(INVALID_CHAR))


    }


    }


    }
    Username.kt

    View full-size slide

  234. sealed class Username {


    data class Valid(val text: String) : Username()


    data class Invalid(val reasons: Set) : Username()


    companion object {


    fun from(possiblyUsername: String): Username {


    possiblyUsername.find { !it.isLetter() }
    ?:
    return Valid(possiblyUsername)


    return Invalid(setOf(INVALID_CHAR))


    }


    }


    }
    Username.kt

    View full-size slide

  235. sealed class Username {


    data class Valid(val text: String) : Username()


    data class Invalid(val reasons: Set) : Username()


    companion object {


    fun from(possiblyUsername: String): Username {


    possiblyUsername.find { !it.isLetter() }
    ?:
    return Valid(possiblyUsername)


    return Invalid(setOf(INVALID_CHAR))


    }


    }


    }
    Username.kt

    View full-size slide

  236. sealed class Username {


    data class Valid(val text: String) : Username()


    data class Invalid(val reasons: Set) : Username()


    companion object {


    fun from(possiblyUsername: String): Username {


    possiblyUsername.find { !it.isLetter() }
    ?:
    return Valid(possiblyUsername)


    return Invalid(setOf(INVALID_CHAR))


    }


    }


    }
    Username.kt

    View full-size slide

  237. sealed class Username {


    data class Valid(val text: String) : Username()


    data class Invalid(val reasons: Set) : Username()


    companion object {


    fun from(possiblyUsername: String): Username {


    possiblyUsername.find { !it.isLetter() }
    ?:
    return Valid(possiblyUsername)


    return Invalid(setOf(INVALID_CHAR))


    }


    }


    }
    Username.kt

    View full-size slide

  238. sealed class Username {


    data class Valid(val text: String) : Username()


    data class Invalid(val reasons: Set) : Username()


    companion object {


    fun from(possiblyUsername: String): Username {


    possiblyUsername.find { !it.isLetter() }
    ?:
    return Valid(possiblyUsername)


    return Invalid(setOf(INVALID_CHAR))


    }


    }


    }
    Username.kt

    View full-size slide

  239. Failure 2 username: Username.Invalid
    View Presenter Model
    username
    failure

    View full-size slide

  240. Failure 2 username: Username.Invalid
    View Presenter Model
    username
    failure

    View full-size slide

  241. Failure 2 username: Username.Invalid
    View Presenter Model
    username
    failure

    View full-size slide

  242. Failure 2 username: Username.Invalid
    View Presenter Model
    username
    failure

    View full-size slide

  243. View Presenter Model
    username username
    failure
    failure
    View Presenter Model
    username
    failure

    View full-size slide

  244. View Presenter Model
    username username
    failure
    failure
    View Presenter Model
    username
    failure

    View full-size slide

  245. View Presenter Model
    username username
    failure
    failure
    View Presenter Model
    username
    failure

    View full-size slide

  246. Username Algebraic Data Type
    View Presenter Model
    username
    Invalid
    Valid

    View full-size slide

  247. Username Algebraic Data Type
    View Presenter Model
    username
    Invalid
    Valid

    View full-size slide

  248. Username Algebraic Data Type
    View Presenter Model
    username
    Invalid
    Valid

    View full-size slide

  249. Username Algebraic Data Type
    View Presenter Model
    username
    Invalid
    Valid

    View full-size slide

  250. What have we learnt?
    • Enforce control
    fl
    ow for data between components

    • Failing fast by reducing data travel between components

    • Reduce coupling between components

    View full-size slide

  251. Where to apply?
    • All layers and components that are within your system boundary, unless you
    have a strong reason not to

    View full-size slide

  252. Impact on Overall System Design
    • Enhances certainty on micro and macroscopic levels

    • Errors are treated as
    fi
    rst-class citizens

    • Reduced range of motion for your data from its point of origin

    • Easy to move towards a functional core and an imperative shell style of architectural pattern

    • Focus moves towards data over actors

    • Promotes value boundaries over call boundaries

    • E
    ff
    ective cure against primitive obsession

    • Reduces defensive programming

    • Promotes value testing over behaviour testing

    View full-size slide

  253. Summary
    • Robustness Principle

    • Total Functions

    • Algebraic Data Types

    • Robustness Principle (Tweaked)

    • Preventing duplication of defensive checks

    • Shaping program’s control
    fl
    ow

    • Failing fast

    View full-size slide

  254. Questions?


    @ragunathjawahar • https:
    /
    /
    ragunath.xyz

    View full-size slide