Share
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
Transcript
257 slides
-
Response? • Successfully creates a user account and returns a
Response 🎉 • null • retrofit2.HttpException • java.net.SocketTimeoutException • i.ll.MakeYourLifeMoreInterestingException 🤷 -
Response? • Successfully creates a user account and returns a
Response 🎉 • null • retrofit2.HttpException • java.net.SocketTimeoutException • i.ll.MakeYourLifeMoreInterestingException 🤷 -
Response? • Successfully creates a user account and returns a
Response 🎉 • null • retrofit2.HttpException • java.net.SocketTimeoutException • i.ll.MakeYourLifeMoreInterestingException 🤷 -
Response? • Successfully creates a user account and returns a
Response 🎉 • null • retrofit2.HttpException • java.net.SocketTimeoutException • i.ll.MakeYourLifeMoreInterestingException 🤷 -
Response? • Successfully creates a user account and returns a
Response 🎉 • null • retrofit2.HttpException • java.net.SocketTimeoutException • i.ll.MakeYourLifeMoreInterestingException 🤷 -
Be conservative in what you send, be liberal in what
you accept Robustness Principle -
Be conservative in what you send, be liberal in what
you accept Robustness Principle -
Robustness Principle Be conservative in what you send, be liberal
in what you accept -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
SignupResponse • Successfully creates a user account • Email already
registered • Validation errors • Connection errors • 5xx server errors • Unknown errors -
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. -
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. -
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. -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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() -
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() -
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() -
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() -
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() -
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() -
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() -
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() -
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() -
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() -
What have we achieved? • Certainty • Convey business ideas
in code • Improved readability • Represent errors as data -
What have we learnt? • Total functions • Algebraic data
types • Robustness principle -
What have we learnt? • Total functions • Algebraic data
types • Robustness principle -
Total Functions Total functions are functions that give you a
valid return value for every combination of valid arguments. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
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. -
// Partial function fun signup(email: String, password: String): Response? //
Total function fun signup(email: String, password: String): SignupResponse Partial vs. Total Functions -
// Partial function fun signup(email: String, password: String): Response? //
Total function fun signup(email: String, password: String): SignupResponse Partial vs. Total Functions -
// Partial function fun signup(email: String, password: String): Response? //
Total function fun signup(email: String, password: String): SignupResponse Partial vs. Total Functions -
// Partial function fun signup(email: String, password: String): Response? //
Total function fun signup(email: String, password: String): SignupResponse Partial vs. Total Functions -
// Partial function fun signup(email: String, password: String): Response? //
Total function fun signup(email: String, password: String): SignupResponse Partial vs. Total Functions -
// Partial function fun signup(email: String, password: String): Response? //
Total function fun signup(email: String, password: String): SignupResponse Partial vs. Total Functions -
// Partial function fun signup(email: String, password: String): Response? //
Total function fun signup(email: String, password: String): SignupResponse Partial vs. Total Functions -
What have we learnt? • Total functions • Algebraic data
types • Robustness principle -
What have we learnt? • Total functions • Algebraic data
types • Robustness principle -
Algebraic Data Types An algebraic data type is a kind
of composite type, i.e., a type formed by combining other types. -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
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<ValidationError>) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() } -
What have we learnt? • Total functions • Algebraic data
types • Robustness principle -
What have we learnt? • Total functions • Algebraic data
types • Robustness principle -
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.) -
fun divide(dividend: Int, divisor: Int): Int { return dividend /
divisor } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Int { return dividend /
divisor } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Int { return dividend /
divisor } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Int { return dividend /
divisor } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Int { return dividend /
divisor } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Int { return dividend /
divisor } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Int { return dividend /
divisor } Arithmetic.kt -
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) -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
fun divide(dividend: Int, divisor: Int): Quotient { return if (divisor
== 0) { Infinity } else { Result(dividend / divisor) } } Arithmetic.kt -
sealed class Quotient { object Infinity : Quotient() data class
Result(val value: Double) : Quotient() } Quotient.kt -
sealed class Quotient { object Infinity : Quotient() data class
Result(val value: Double) : Quotient() } Quotient.kt -
sealed class Quotient { object Infinity : Quotient() data class
Result(val value: Double) : Quotient() } Quotient.kt -
sealed class Quotient { object Infinity : Quotient() data class
Result(val value: Double) : Quotient() } Quotient.kt -
sealed class Quotient { object Infinity : Quotient() data class
Result(val value: Double) : Quotient() } Quotient.kt -
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 -
Be conservative in what you send, be liberal in what
you accept conservative -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
fun divide(dividend: Int, divisor: Integer.NonZero): Int { return dividend /
divisor.number } Arithmetic.kt -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
val divisor = Integer.from(4) if (divisor is NonZero) { val
quotient = divide(9, divisor) // Do fancy things! } else { // Fail fast… } Usage -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
// 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 -
Where to apply? • All layers and components that are
within your system boundary -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
Be conservative in what you send, be liberal in what
you accept conservative -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
fun countFiles(directory: Directory.Valid, extension: String): Int { return directory .location
.listFiles() ?. filter { it.name.endsWith(".$extension") } ?. count() ?: 0 } FileStats.kt -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
val directory = Directory.from("~/Documents/Finance") if (directory is Directory.Valid) { val
spreadSheetsCount = countFiles(directory, "xlsx") // Do fancy things! } else { // Fail fast… } Usage -
What have we learnt? • Protecting users of a type
from making unnecessary defensive checks -
Where to apply? • All layers and components that are
within your system boundary -
sealed class Username { data class Valid(val text: String) :
Username() data class Invalid(val reasons: Set<Reason>) : Username() companion object { fun from(possiblyUsername: String): Username { possiblyUsername.find { !it.isLetter() } ?: return Valid(possiblyUsername) return Invalid(setOf(INVALID_CHAR)) } } } Username.kt -
sealed class Username { data class Valid(val text: String) :
Username() data class Invalid(val reasons: Set<Reason>) : Username() companion object { fun from(possiblyUsername: String): Username { possiblyUsername.find { !it.isLetter() } ?: return Valid(possiblyUsername) return Invalid(setOf(INVALID_CHAR)) } } } Username.kt -
sealed class Username { data class Valid(val text: String) :
Username() data class Invalid(val reasons: Set<Reason>) : Username() companion object { fun from(possiblyUsername: String): Username { possiblyUsername.find { !it.isLetter() } ?: return Valid(possiblyUsername) return Invalid(setOf(INVALID_CHAR)) } } } Username.kt -
sealed class Username { data class Valid(val text: String) :
Username() data class Invalid(val reasons: Set<Reason>) : Username() companion object { fun from(possiblyUsername: String): Username { possiblyUsername.find { !it.isLetter() } ?: return Valid(possiblyUsername) return Invalid(setOf(INVALID_CHAR)) } } } Username.kt -
sealed class Username { data class Valid(val text: String) :
Username() data class Invalid(val reasons: Set<Reason>) : Username() companion object { fun from(possiblyUsername: String): Username { possiblyUsername.find { !it.isLetter() } ?: return Valid(possiblyUsername) return Invalid(setOf(INVALID_CHAR)) } } } Username.kt -
sealed class Username { data class Valid(val text: String) :
Username() data class Invalid(val reasons: Set<Reason>) : Username() companion object { fun from(possiblyUsername: String): Username { possiblyUsername.find { !it.isLetter() } ?: return Valid(possiblyUsername) return Invalid(setOf(INVALID_CHAR)) } } } Username.kt -
What have we learnt? • Enforce control fl ow for
data between components • Failing fast by reducing data travel between components • Reduce coupling between components -
Where to apply? • All layers and components that are
within your system boundary, unless you have a strong reason not to -
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 -
Summary • Robustness Principle • Total Functions • Algebraic Data
Types • Robustness Principle (Tweaked) • Preventing duplication of defensive checks • Shaping program’s control fl ow • Failing fast