Share
Embed
Railway Oriented Programming with Kotlin
Many examples in Kotlin assume that you are always on the "happy path". But real-world applications must deal with a lot of types of errors: validation, network, and others.
So, how do you handle all of this?
Marcello Galhardo
June 05, 2019
Transcript
82 slides
-
Marcello Galhardo [email protected] A functional approach to error handling Railway
Oriented Programming with Kotlin. -
“As a user I want to update my name and
email address.” -
Button clicks send Action to ViewModel ViewModel invokes UseCase to
validate and canonicalise Action data -
Button clicks send Action to ViewModel ViewModel invokes UseCase to
validate and canonicalise Action data UseCase ask Repository to update user data -
Button clicks send Action to ViewModel ViewModel invokes UseCase to
validate and canonicalise Action data UseCase ask Repository to update user data Returns result to UI -
Action.kt sealed class Action { data class UpdateUser( val id:
UserId, val name: String, val email: String ) : Action() } -
Action.kt sealed class Action { data class UpdateUser( val id:
UserId, val name: String, val email: String ) : Action() } -
Action.kt sealed class Action { data class UpdateUser( val id:
UserId, val name: String, val email: String ) : Action() } -
View.kt // Action dispatcher in a View okButton.setOnClickListener { val
name = nameTextField.value val email = emailTextField.value val action = Action.UpdateUser(userId, name, email) viewModel.dispatch(action) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
Functions // ValidateUser.kt fun validate(action: Action.UpdateUser): Boolean // CanonicalizeEmail.kt fun
canonicalizeEmail(action: Action.UpdateUser): String // UserRepository.kt @Throws(Exception::class) fun Repository.getUserById(id: UserId): User? @Throws(Exception::class) fun Repository.update(user: User) -
Functions // ValidateUser.kt fun validate(action: Action.UpdateUser): Boolean // CanonicalizeEmail.kt fun
canonicalizeEmail(action: Action.UpdateUser): String // UserRepository.kt @Throws(Exception::class) fun Repository.getUserById(id: UserId): User? @Throws(Exception::class) fun Repository.update(user: User) -
Functions // ValidateUser.kt fun validate(action: Action.UpdateUser): Boolean // CanonicalizeEmail.kt fun
canonicalizeEmail(action: Action.UpdateUser): String // UserRepository.kt @Throws(Exception::class) fun Repository.getUserById(id: UserId): User? @Throws(Exception::class) fun Repository.update(user: User) -
Functions // ValidateUser.kt fun validate(action: Action.UpdateUser): Boolean // CanonicalizeEmail.kt fun
canonicalizeEmail(action: Action.UpdateUser): String // UserRepository.kt @Throws(Exception::class) fun Repository.getUserById(id: UserId): User? @Throws(Exception::class) fun Repository.update(user: User) -
“As a user I want to update my name and
email address… …and see error messages when something goes wrong!" -
“As a user I want to update my name and
email address… …and see error messages when something goes wrong!" -
Button clicks send Action to ViewModel ViewModel invokes UseCase to
validate and canonicalise Action data UseCase ask Repository to update user data Returns result to UI -
Button clicks send Action to ViewModel ViewModel invokes UseCase to
validate and canonicalise Action data UseCase ask Repository to update user data Returns result to UI -
Name is blank or email not valid Button clicks send
Action to ViewModel ViewModel invokes UseCase to validate and canonicalise Action data UseCase ask Repository to update user data Returns result to UI -
Name is blank or email not valid Button clicks send
Action to ViewModel ViewModel invokes UseCase to validate and canonicalise Action data UseCase ask Repository to update user data Returns result to UI -
Name is blank or email not valid User not found
Button clicks send Action to ViewModel ViewModel invokes UseCase to validate and canonicalise Action data UseCase ask Repository to update user data Returns result to UI -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { validate(action) val
canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { val isValid
= validate(action) if (!isValid) { return Result.error(UserNotValidException()) } val canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { val isValid
= validate(action) if (!isValid) { return Result.error(UserNotValidException()) } val canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { val isValid
= validate(action) if (!isValid) { return Result.error(UserNotValidException()) } val canonicalizedEmail = canonicalizeEmail(action) val user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { val isValid
= validate(action) if (!isValid) { return Result.error(UserNotValidException()) } val canonicalizedEmail = canonicalizeEmail(action) var user = null try { user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) } catch (error: Exception) { return Result.error(error) } return Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { val isValid
= validate(action) if (!isValid) { return Result.error(UserNotValidException()) } val canonicalizedEmail = canonicalizeEmail(action) var user = null try { user = repository.getUserById(id).copy( name = action.name, email = canonicalizedEmail ) repository.update(user) } catch (error: Exception) { return Result.error(error) } return Result.success(user) } -
• Each use case will be equivalent to a single
function • The function will return a sum type with two cases: Success or Failure • The use case function will be built from a series of smaller functions, each representing one step in a data flow • The errors from each step will be combined into a single failure -
• Each use case will be equivalent to a single
function • The function will return a sum type with two cases: Success, Failure • The use case function will be built from a series of smaller functions, each representing one step in a data flow • The errors from each step will be combined into a single failure -
• Each use case will be equivalent to a single
function • The function will return a sum type with two cases: Success, Failure • The use case function will be built from a series of smaller functions, each representing one step in a data flow • The errors from each step will be combined into a single failure -
• Each use case will be equivalent to a single
function • The function will return a sum type with two cases: Success, Failure • The use case function will be built from a series of smaller functions, each representing one step in a data flow • Each step will be combined into a single result -
The following Result class and methods are simplified/custom versions for
easy understanding -
bit.do/kotlin-std-result sealed class Result<Value> { data class Success( val value:
Value ): Result<Value> data class Failure( val error: Exception ): Result<Nothing> } -
bit.do/kotlin-std-result sealed class Result<Value> { data class Success( val value:
Value ): Result<Value> data class Failure( val error: Exception ): Result<Nothing> } -
bit.do/kotlin-std-result sealed class Result<Value> { data class Success( val value:
Value ): Result<Value> data class Failure( val error: Exception ): Result<Nothing> } -
bit.do/kotlin-std-result sealed class Result<Value> { data class Success( val value:
Value ): Result<Value> data class Failure( val error: String ): Result<Nothing> } -
public inline fun <R, T> Result<T>.map(transform: (value: T) -> R):
Result<R> { return when { isSuccess -> Result.success(transform(value as T)) else -> Result(value) } } bit.do/kotlin-std-result -
public inline fun <R, T> Result<T>.map(transform: (value: T) -> R):
Result<R> { return when { isSuccess -> Result.success(transform(value as T)) else -> Result(value) } } bit.do/kotlin-std-result -
public inline fun <R, T> Result<T>.map(transform: (value: T) -> R):
Result<R> { return when { isSuccess -> Result.success(transform(value as T)) else -> Result(value) } } bit.do/kotlin-std-result -
public inline fun <R, T> Result<T>.map(transform: (value: T) -> R):
Result<R> { return when { isSuccess -> Result.success(transform(value as T)) else -> Result(value) } } bit.do/kotlin-std-result -
public inline fun <R, T> Result<T>.flatMap( transform: (value: T) ->
Result<R> ): Result<R> { return when { isSuccess -> transform(value as T) else -> Result(value) } } bit.do/kotlin-std-result -
public inline fun <R, T> Result<T>.flatMap( transform: (value: T) ->
Result<R> ): Result<R> { return when { isSuccess -> transform(value as T) else -> Result(value) } } bit.do/kotlin-std-result -
public inline fun <R, T> Result<T>.flatMap( transform: (value: T) ->
Result<R> ): Result<R> { return when { isSuccess -> transform(value as T) else -> Result(value) } } bit.do/kotlin-std-result -
public inline fun <R, T> Result<T>.flatMap( transform: (value: T) ->
Result<R> ): Result<R> { return when { isSuccess -> transform(value as T) else -> Result(value) } } bit.do/kotlin-std-result -
ViewModel invokes UseCase to validate and canonicalise Action data Failure
UseCase ask Repository to update user data ? Success -
Success ViewModel invokes UseCase to validate and canonicalise Action data
UseCase ask Repository to update user data Failure Success Failure ? -
Success ViewModel invokes UseCase to validate and canonicalise Action data
Failure UseCase ask Repository to update user data Failure Success -
GetUserById.kt fun getUserById(input: Action.UpdateUser): Result<User> { val user = repository.getUserByIdOrNull(input.id)
return when { user == null -> Result.failure("User not found.") else -> Result.success(user) } } -
NameNotBlank.kt fun nameNotBlank(user: User) = when { user.name == ""
-> Result.failure("Name must not be blank.") else -> Result.success(user) } -
NameIsBelowMaxLength.kt fun nameIsBelowMaxLength(user: User) = when { user.name.length > 50
-> Result.failure("Name must not be longer than 50 chars.") else -> Result.success(user) } -
EmailNotBlank.kt fun emailNotBlank(user: User) = when { user.email == ""
-> Result.failure("Email must not be blank.") else -> Result.success(user) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { return getUserById(action.id)
.map { user -> user.copy(name = action.name) } .map { user -> user.copy(email = action.email) } .map(::nameNotBlank) .map(::nameIsBelowMaxLength) .map(::emailNotBlank) .map(::canonicalizeEmail) .map(::saveUser) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { return getUserById(action.id)
.map { user -> user.copy(name = action.name) } .map { user -> user.copy(email = action.email) } .map(::nameNotBlank) .map(::nameIsBelowMaxLength) .map(::emailNotBlank) .map(::canonicalizeEmail) .map(::saveUser) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { return getUserById(action.id)
.map { user -> user.copy(name = action.name) } .map { user -> user.copy(email = action.email) } .map(::nameNotBlank) .map(::nameIsBelowMaxLength) .map(::emailNotBlank) .map(::canonicalizeEmail) .map(::saveUser) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { return getUserById(action.id)
.map { user -> user.copy(name = action.name) } .map { user -> user.copy(email = action.email) } .flatMap(::nameNotBlank) .flatMap(::nameIsBelowMaxLength) .flatMap(::emailNotBlank) .map(::canonicalizeEmail) .map(::saveUser) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { return getUserById(action.id)
.map { user -> user.copy(name = action.name) } .map { user -> user.copy(email = action.email) } .flatMap(::nameNotBlank) .flatMap(::nameIsBelowMaxLength) .flatMap(::emailNotBlank) .flatMap(::canonicalizeEmail) .map(::saveUser) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { return getUserById(action.id)
.map { user -> user.copy(name = action.name) } .map { user -> user.copy(email = action.email) } .flatMap(::nameNotBlank) .flatMap(::nameIsBelowMaxLength) .flatMap(::emailNotBlank) .flatMap(::canonicalizeEmail) .flatMap(::saveUser) } -
UpdateUser.kt fun updateUser( action: Action.UpdateUser ): Result<User> { return getUserById(action.id)
.map { user -> user.copy(name = action.name) } .map { user -> user.copy(email = action.email) } .flatMap(::nameNotBlank) .flatMap(::nameIsBelowMaxLength) .flatMap(::emailNotBlank) .flatMap(::canonicalizeEmail) .flatMap(::saveUser) } -
ViewModel.kt fun dispatch(action: Action) { useCase.invoke() .onSuccess { // Do
something cool! }.onFailure { // Ops, something went wrong… } } -
ViewModel.kt fun dispatch(action: Action) { updateUser(action) .onSuccess { // Do
something cool! }.onFailure { // Ops, something went wrong… } } -
ViewModel.kt fun dispatch(action: Action) { updateUser(action) .onSuccess { value ->
// Do something cool! }.onFailure { // Ops, something went wrong… } } -
ViewModel.kt fun dispatch(action: Action) { updateUser(action) .onSuccess { value ->
// Do something cool! }.onFailure { error -> // Ops, something went wrong… } } -
• A strategy for handling errors in a functional way
• Design for errors: unhappy paths are requirements too • Do not use Exception handling for Control Flow. “Do or do not, there is no try” -
• A strategy for handling errors in a functional way
• Design for errors: unhappy paths are requirements too • Do not use Exception handling for Control Flow. “Do or do not, there is no try” -
• A strategy for handling errors in a functional way
• Design for errors: unhappy paths are requirements too • Do not use Exception handling for Control Flow “Do or do not, there is no try” -
• A strategy for handling errors in a functional way
• Design for errors: unhappy paths are requirements too • Do not use Exception handling for Control Flow “Do or do not, there is no try.”