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 Slide

  2. Write code that communicates well.

    View Slide

  3. Example 1


    API Call / External Systems

    View Slide

  4. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  5. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  6. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  7. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  8. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  9. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  10. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

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

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View Slide

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

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View Slide

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

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View Slide

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

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View Slide

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

    • null

    • retrofit2.HttpException


    • java.net.SocketTimeoutException


    • i.ll.MakeYourLifeMoreInterestingException 🤷

    View Slide

  16. 😊 😕 😨
    Caller’s emotions

    View Slide

  17. 😊 😕 😨
    Caller’s emotions

    View Slide

  18. 😊 😕 😨
    Caller’s emotions

    View Slide

  19. 😊 😕 😨
    Caller’s emotions

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  23. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  24. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  25. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  26. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  27. interface AccountsApi {


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


    }
    AccountsApi.kt

    View Slide

  28. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View Slide

  29. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View Slide

  30. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View Slide

  31. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View Slide

  32. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View Slide

  33. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View Slide

  34. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View Slide

  35. SignupResponse
    • Successfully creates a user account

    • Email already registered

    • Validation errors

    • Connection errors

    • 5xx server errors

    • Unknown errors

    View 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Slide

  57. Enforcing exhaustive when statements

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

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

    View 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 Slide

  59. 😊 😌
    Caller’s emotions

    View Slide

  60. 😊 😌
    Caller’s emotions

    View Slide

  61. 😊 😌
    Caller’s emotions

    View Slide

  62. What have we achieved?
    • Certainty

    • Convey business ideas in code

    • Improved readability

    • Represent errors as data

    View Slide

  63. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View Slide

  64. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View Slide

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

    View 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Slide

  81. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View Slide

  82. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View 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 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 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 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 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 Slide

  88. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View Slide

  89. What have we learnt?
    • Total functions

    • Algebraic data types

    • Robustness principle

    View 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 Slide

  91. Example 2


    Division / Exceptions

    View Slide

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


    return dividend / divisor


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor


    }
    Arithmetic.kt

    View Slide

  99. divisor = 0

    View Slide

  100. 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 Slide

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

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

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


    return if (divisor
    ==
    0) {


    Infinity


    } else {


    Result(dividend / divisor)


    }


    }
    Arithmetic.kt

    View Slide

  112. sealed class Quotient {


    object Infinity : Quotient()


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


    }
    Quotient.kt

    View Slide

  113. sealed class Quotient {


    object Infinity : Quotient()


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


    }
    Quotient.kt

    View Slide

  114. sealed class Quotient {


    object Infinity : Quotient()


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


    }
    Quotient.kt

    View Slide

  115. sealed class Quotient {


    object Infinity : Quotient()


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


    }
    Quotient.kt

    View Slide

  116. sealed class Quotient {


    object Infinity : Quotient()


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


    }
    Quotient.kt

    View Slide

  117. 🤔

    View Slide

  118. 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 Slide

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

    View Slide

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

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View Slide

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


    return dividend / divisor.number


    }
    Arithmetic.kt

    View 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 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 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 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 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 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 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 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 Slide

  139. 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 Slide

  140. 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 Slide

  141. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  142. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  143. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  144. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  145. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  146. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  147. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  148. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

  149. val divisor = Integer.from(4)


    if (divisor is NonZero) {


    val quotient = divide(9, divisor)


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View 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 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 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 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 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 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 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 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 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 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 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 Slide

  161. //
    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 Slide

  162. //
    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 Slide

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

    View Slide

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

    View Slide

  165. Example 3


    File / Defensive Programming

    View Slide

  166. File

    View 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 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 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 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 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 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 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 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 Slide

  175. 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 Slide

  176. 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 Slide

  177. 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 Slide

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

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View Slide

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


    return directory


    .location


    .listFiles()


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


    ?.
    count()
    ?:
    0


    }
    FileStats.kt

    View 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 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 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 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 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 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 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 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 Slide

  197. 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 Slide

  198. 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 Slide

  199. 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 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 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 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 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 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 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 Slide

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


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

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


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

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


    if (directory is Directory.Valid) {


    val spreadSheetsCount = countFiles(directory, "xlsx")


    //
    Do fancy things!


    } else {


    //
    Fail fast…


    }
    Usage

    View Slide

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

    View Slide

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

    View Slide

  211. Example 4


    Username / Primitive Obsession

    View Slide

  212. /
    /
    Failing fast…

    View Slide

  213. View Presenter Model
    Model - View - Presenter

    View Slide

  214. View Presenter Model
    Model - View - Presenter

    View Slide

  215. View Presenter Model
    Model - View - Presenter

    View Slide

  216. View Presenter Model
    Model - View - Presenter

    View Slide

  217. View Presenter Model
    Model - View - Presenter

    View Slide

  218. View Presenter Model
    Model - View - Presenter

    View Slide

  219. View Presenter Model
    Model - View - Presenter

    View Slide

  220. View Presenter Model
    Model - View - Presenter

    View Slide

  221. View Presenter Model
    Model - View - Presenter

    View Slide

  222. View Presenter Model
    Model - View - Presenter

    View Slide

  223. View Presenter Model
    Model - View - Presenter

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  231. Data Behavior

    View Slide

  232. Data Behavior

    View Slide

  233. Data Behavior

    View Slide

  234. Data Behavior

    View Slide

  235. Data Behavior

    View 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 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 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 Slide

  239. 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 Slide

  240. 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 Slide

  241. 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 Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  246. View Presenter Model
    username username
    failure
    failure
    View Presenter Model
    username
    failure

    View Slide

  247. View Presenter Model
    username username
    failure
    failure
    View Presenter Model
    username
    failure

    View Slide

  248. View Presenter Model
    username username
    failure
    failure
    View Presenter Model
    username
    failure

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  253. 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 Slide

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

    View Slide

  255. 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 Slide

  256. 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 Slide

  257. Questions?


    @ragunathjawahar • https:
    /
    /
    ragunath.xyz

    View Slide