├── .editorconfig ├── .gitignore ├── README.md ├── build.gradle.kts ├── docker-compose.yml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main └── kotlin │ ├── Main.kt │ └── io │ └── github │ └── myuwono │ └── petshop │ ├── Types.kt │ └── requirement7 │ ├── ContextReceiversPetService.kt │ ├── ExceptionPetService.kt │ ├── SealedClassEarlyReturnPetService.kt │ ├── SealedClassPetService.kt │ ├── TaggedTypesFlatMapPetService.kt │ └── TaggedTypesPetService.kt └── test └── kotlin └── io └── github └── myuwono └── petshop └── Level1Test.kt /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://github.com/JetBrains/kotlin-playground/blob/master/.editorconfig 2 | # EditorConfig helps developers define and maintain consistent 3 | # coding styles between different editors and IDEs 4 | # editorconfig.org 5 | 6 | root = true 7 | 8 | 9 | [*] 10 | 11 | # Change these settings to your own preference 12 | indent_style = space 13 | indent_size = 4 14 | 15 | # We recommend you to keep these unchanged 16 | end_of_line = lf 17 | charset = utf-8 18 | trim_trailing_whitespace = true 19 | insert_final_newline = true 20 | 21 | # To override IDEA default 120 columns 22 | max_line_length = 160 23 | ij_visual_guides = 140, 160 24 | 25 | [*.md] 26 | trim_trailing_whitespace = false 27 | 28 | 29 | [*.{kt, java}] 30 | ij_kotlin_imports_layout = * 31 | indent_size = 2 32 | ij_kotlin_name_count_to_use_star_import = 999 33 | ij_kotlin_name_count_to_use_star_import_for_members = 999 34 | ij_java_class_count_to_use_import_on_demand = 999 35 | ktlint_disabled_rules = no-unit-return 36 | 37 | [*.kts] 38 | ij_kotlin_imports_layout = * 39 | indent_size = 2 40 | ij_kotlin_name_count_to_use_star_import = 999 41 | ij_kotlin_name_count_to_use_star_import_for_members = 999 42 | ij_java_class_count_to_use_import_on_demand = 999 43 | ktlint_disabled_rules = no-unit-return 44 | 45 | [*.{tf, yml, yaml}] 46 | indent_size = 2 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/ 3 | **/*.iml 4 | **/build/ 5 | 6 | **/*.DS_Store 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # typed-error-handling-demo 2 | 3 | This repository is created as a supporting material in the study in "Typed Error Handling in Kotlin". 4 | 5 | The approach explored in this repository includes: 6 | - Exception based error handling 7 | - Vanilla sealed class chaining 8 | - Vanilla sealed class with early returns 9 | - Arrow `Raise` with context receivers 10 | - Arrow with `either { }` builder 11 | - Arrow vanilla `Either` with flatMap chaining 12 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.dsl.KotlinVersion 2 | 3 | plugins { 4 | kotlin("jvm") version "1.8.20" 5 | id("org.sonarqube") version "4.0.0.2929" 6 | id("org.jlleitschuh.gradle.ktlint") version "11.3.1" 7 | application 8 | } 9 | 10 | group = "io.github.myuwono" 11 | version = "1.0-SNAPSHOT" 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | implementation("io.arrow-kt:arrow-core:1.2.0-RC") 19 | implementation("io.arrow-kt:arrow-fx-coroutines:1.2.0-RC") 20 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4") 21 | 22 | testImplementation("io.kotest:kotest-runner-junit5:5.5.5") 23 | testImplementation("io.kotest:kotest-property:5.5.5") 24 | testImplementation("io.kotest.extensions:kotest-assertions-arrow:1.3.1") 25 | testImplementation("io.kotest.extensions:kotest-property-arrow:1.3.1") 26 | } 27 | 28 | tasks { 29 | test { 30 | useJUnitPlatform() 31 | testLogging { 32 | setExceptionFormat("full") 33 | setEvents(listOf("passed", "skipped", "failed", "standardOut", "standardError")) 34 | } 35 | } 36 | 37 | compileKotlin { 38 | compilerOptions { 39 | freeCompilerArgs.addAll( 40 | "-progressive", 41 | "-java-parameters", 42 | "-Xcontext-receivers", 43 | "-opt-in=kotlin.time.ExperimentalTime", 44 | "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi", 45 | "-opt-in=kotlin.RequiresOptIn" 46 | ) 47 | 48 | languageVersion.set(KotlinVersion.KOTLIN_2_0) 49 | apiVersion.set(KotlinVersion.KOTLIN_2_0) 50 | } 51 | } 52 | } 53 | 54 | kotlin { 55 | jvmToolchain(17) 56 | } 57 | 58 | application { 59 | mainClass.set("MainKt") 60 | } 61 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | sonarqube: 3 | image: sonarqube 4 | ports: 5 | - "9000:9000" 6 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx512m -Dfile.encoding=UTF-8 -XX:+UseParallelGC 2 | org.gradle.parallel=true 3 | org.gradle.caching=true 4 | org.gradle.workers.max=3 5 | 6 | # Kotlin configuration 7 | kotlin.incremental=true 8 | kotlin.incremental.useClasspathSnapshot=true 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myuwono/typed-error-handling-demo/051062ad8d4899146dd3a892c086e0207e629f6e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | 2 | rootProject.name = "typed-error-handling" 3 | -------------------------------------------------------------------------------- /src/main/kotlin/Main.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | println("Hello World!") 3 | 4 | // Try adding program arguments via Run/Debug configuration. 5 | // Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html. 6 | println("Program arguments: ${args.joinToString()}") 7 | } 8 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/myuwono/petshop/Types.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop 2 | 3 | import java.time.LocalDate 4 | 5 | data class PetId(val value: String) 6 | data class PetOwnerId(val value: String) 7 | data class MicrochipId(val value: String) 8 | 9 | data class Microchip(val id: MicrochipId, val petOwnerId: PetOwnerId, val petId: PetId) 10 | 11 | enum class PetType { Dog, Cat } 12 | enum class PetGender { Male, Female } 13 | 14 | data class Pet( 15 | val id: PetId, 16 | val microchipId: MicrochipId, 17 | val name: String, 18 | val birthDate: LocalDate, 19 | val petType: PetType, 20 | val breed: String, 21 | val gender: PetGender 22 | ) 23 | 24 | data class PetOwner(val id: PetOwnerId, val name: String) 25 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/myuwono/petshop/requirement7/ContextReceiversPetService.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop.requirement7 2 | 3 | import arrow.core.raise.Raise 4 | import arrow.core.raise.ensure 5 | import arrow.core.raise.recover 6 | import io.github.myuwono.petshop.Microchip 7 | import io.github.myuwono.petshop.MicrochipId 8 | import io.github.myuwono.petshop.Pet 9 | import io.github.myuwono.petshop.PetGender 10 | import io.github.myuwono.petshop.PetId 11 | import io.github.myuwono.petshop.PetOwner 12 | import io.github.myuwono.petshop.PetOwnerId 13 | import io.github.myuwono.petshop.PetType 14 | import java.time.LocalDate 15 | 16 | class ContextReceiversPetService( 17 | private val microchipStore: MicrochipStore, 18 | private val petStore: PetStore, 19 | private val petOwnerStore: PetOwnerStore 20 | ) { 21 | 22 | context(Raise) 23 | suspend fun updatePetDetails( 24 | petId: PetId, 25 | petOwnerId: PetOwnerId, 26 | petUpdate: PetUpdate 27 | ): Pet { 28 | val pet = petStore.getPet(petId) ?: raise(UpdatePetDetailsFailure.PetNotFound) 29 | val owner = petOwnerStore.getPetOwner(petOwnerId) ?: raise(UpdatePetDetailsFailure.OwnerNotFound) 30 | val microchip = microchipStore.getMicrochip(pet.microchipId) ?: raise(UpdatePetDetailsFailure.MicrochipNotFound) 31 | 32 | ensure(microchip.petId == pet.id) { UpdatePetDetailsFailure.InvalidMicrochip } 33 | ensure(microchip.petOwnerId == owner.id) { UpdatePetDetailsFailure.OwnerMismatch } 34 | 35 | petUpdate.name?.let { checkNamePolicy(it) } 36 | 37 | return recover({ petStore.updatePet(pet.id, petUpdate) }) { updatePetFailure -> 38 | when (updatePetFailure) { 39 | UpdatePetFailure.IllegalUpdate -> raise(UpdatePetDetailsFailure.InvalidUpdate) 40 | UpdatePetFailure.NotFound -> raise(UpdatePetDetailsFailure.PetNotFound) 41 | } 42 | } 43 | } 44 | 45 | context(Raise) 46 | private fun checkNamePolicy(name: String): Unit = ensure(name.isNotBlank()) { 47 | UpdatePetDetailsFailure.InvalidUpdate 48 | } 49 | 50 | interface MicrochipStore { 51 | suspend fun getMicrochip(microchipId: MicrochipId): Microchip? 52 | } 53 | 54 | interface PetOwnerStore { 55 | suspend fun getPetOwner(petOwnerId: PetOwnerId): PetOwner? 56 | } 57 | 58 | interface PetStore { 59 | suspend fun getPet(petId: PetId): Pet? 60 | 61 | context(Raise) 62 | suspend fun updatePet(petId: PetId, petUpdate: PetUpdate): Pet 63 | } 64 | 65 | data class PetUpdate( 66 | val microchipId: MicrochipId? = null, 67 | val name: String? = null, 68 | val birthDate: LocalDate? = null, 69 | val petType: PetType? = null, 70 | val breed: String? = null, 71 | val gender: PetGender? = null 72 | ) 73 | 74 | sealed class UpdatePetFailure { 75 | object NotFound : UpdatePetFailure() 76 | object IllegalUpdate : UpdatePetFailure() 77 | } 78 | 79 | sealed class UpdatePetDetailsFailure { 80 | object OwnerNotFound : UpdatePetDetailsFailure() 81 | object PetNotFound : UpdatePetDetailsFailure() 82 | object MicrochipNotFound : UpdatePetDetailsFailure() 83 | object InvalidMicrochip : UpdatePetDetailsFailure() 84 | object OwnerMismatch : UpdatePetDetailsFailure() 85 | object InvalidUpdate : UpdatePetDetailsFailure() 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/myuwono/petshop/requirement7/ExceptionPetService.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop.requirement7 2 | 3 | import io.github.myuwono.petshop.Microchip 4 | import io.github.myuwono.petshop.MicrochipId 5 | import io.github.myuwono.petshop.Pet 6 | import io.github.myuwono.petshop.PetGender 7 | import io.github.myuwono.petshop.PetId 8 | import io.github.myuwono.petshop.PetOwner 9 | import io.github.myuwono.petshop.PetOwnerId 10 | import io.github.myuwono.petshop.PetType 11 | import java.time.LocalDate 12 | 13 | class ExceptionPetService( 14 | private val microchipStore: MicrochipStore, 15 | private val petStore: PetStore, 16 | private val petOwnerStore: PetOwnerStore 17 | ) { 18 | 19 | suspend fun updatePetDetails( 20 | petId: PetId, 21 | petOwnerId: PetOwnerId, 22 | petUpdate: PetUpdate 23 | ): Pet = try { 24 | val pet = petStore.getPet(petId) 25 | val owner = petOwnerStore.getPetOwner(petOwnerId) 26 | val microchip = microchipStore.getMicrochip(pet.microchipId) 27 | 28 | if (microchip.petId != pet.id) { 29 | throw UpdatePetDetailsException.InvalidMicrochip() 30 | } 31 | 32 | if (microchip.petOwnerId != owner.id) { 33 | throw UpdatePetDetailsException.OwnerMismatch() 34 | } 35 | 36 | petUpdate.name?.let { checkNamePolicy(it) } 37 | 38 | petStore.updatePet(petId, petUpdate) 39 | } catch (ex: Throwable) { 40 | when (ex) { 41 | is PetNotFoundException -> throw UpdatePetDetailsException.PetNotFound(ex) 42 | is PetOwnerNotFoundException -> throw UpdatePetDetailsException.OwnerNotFound(ex) 43 | is MicrochipNotFoundException -> throw UpdatePetDetailsException.MicrochipNotFound(ex) 44 | is CheckNameFailedException -> throw UpdatePetDetailsException.InvalidUpdate(ex) 45 | is UpdatePetException -> when (ex) { 46 | is UpdatePetException.IllegalUpdate -> throw UpdatePetDetailsException.InvalidUpdate(ex) 47 | is UpdatePetException.NotFound -> throw UpdatePetDetailsException.PetNotFound(ex) 48 | } 49 | 50 | else -> throw ex 51 | } 52 | } 53 | 54 | private fun checkNamePolicy(name: String): Unit = if (name.isNotBlank()) Unit else throw CheckNameFailedException() 55 | 56 | data class CheckNameFailedException(override val cause: Throwable? = null) : RuntimeException() 57 | 58 | interface MicrochipStore { 59 | suspend fun getMicrochip(microchipId: MicrochipId): Microchip 60 | } 61 | 62 | data class MicrochipNotFoundException(override val cause: Throwable? = null) : RuntimeException() 63 | 64 | interface PetOwnerStore { 65 | suspend fun getPetOwner(petOwnerId: PetOwnerId): PetOwner 66 | } 67 | 68 | data class PetOwnerNotFoundException(override val cause: Throwable? = null) : RuntimeException() 69 | 70 | interface PetStore { 71 | suspend fun getPet(petId: PetId): Pet 72 | suspend fun updatePet(petId: PetId, petUpdate: PetUpdate): Pet 73 | } 74 | 75 | data class PetUpdate( 76 | val microchipId: MicrochipId? = null, 77 | val name: String? = null, 78 | val birthDate: LocalDate? = null, 79 | val petType: PetType? = null, 80 | val breed: String? = null, 81 | val gender: PetGender? = null 82 | ) 83 | 84 | data class PetNotFoundException(override val cause: Throwable? = null) : RuntimeException() 85 | 86 | sealed class UpdatePetException : RuntimeException() { 87 | data class NotFound(override val cause: Throwable? = null) : UpdatePetException() 88 | data class IllegalUpdate(override val cause: Throwable? = null) : UpdatePetException() 89 | } 90 | 91 | sealed class UpdatePetDetailsException : RuntimeException() { 92 | data class OwnerNotFound(override val cause: Throwable? = null) : UpdatePetDetailsException() 93 | data class PetNotFound(override val cause: Throwable? = null) : UpdatePetDetailsException() 94 | data class MicrochipNotFound(override val cause: Throwable? = null) : UpdatePetDetailsException() 95 | data class InvalidMicrochip(override val cause: Throwable? = null) : UpdatePetDetailsException() 96 | data class OwnerMismatch(override val cause: Throwable? = null) : UpdatePetDetailsException() 97 | data class InvalidUpdate(override val cause: Throwable? = null) : UpdatePetDetailsException() 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/myuwono/petshop/requirement7/SealedClassEarlyReturnPetService.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop.requirement7 2 | 3 | import io.github.myuwono.petshop.Microchip 4 | import io.github.myuwono.petshop.MicrochipId 5 | import io.github.myuwono.petshop.Pet 6 | import io.github.myuwono.petshop.PetGender 7 | import io.github.myuwono.petshop.PetId 8 | import io.github.myuwono.petshop.PetOwner 9 | import io.github.myuwono.petshop.PetOwnerId 10 | import io.github.myuwono.petshop.PetType 11 | import java.time.LocalDate 12 | 13 | class SealedClassEarlyReturnPetService( 14 | private val microchipStore: MicrochipStore, 15 | private val petStore: PetStore, 16 | private val petOwnerStore: PetOwnerStore 17 | ) { 18 | suspend fun updatePetDetails( 19 | petId: PetId, 20 | petOwnerId: PetOwnerId, 21 | petUpdate: PetUpdate 22 | ): UpdatePetDetailsResult { 23 | val pet = petStore.getPet(petId) ?: return UpdatePetDetailsResult.PetNotFound 24 | val owner = petOwnerStore.getPetOwner(petOwnerId) ?: return UpdatePetDetailsResult.OwnerNotFound 25 | val microchip = microchipStore.getMicrochip(pet.microchipId) ?: return UpdatePetDetailsResult.MicrochipNotFound 26 | 27 | if (microchip.petId != pet.id) { 28 | return UpdatePetDetailsResult.InvalidMicrochip 29 | } 30 | 31 | if (microchip.petOwnerId != owner.id) { 32 | return UpdatePetDetailsResult.OwnerMismatch 33 | } 34 | 35 | petUpdate.name?.let { name -> 36 | when (checkNamePolicy(name)) { 37 | CheckNamePolicyResult.Failure -> return UpdatePetDetailsResult.InvalidUpdate 38 | CheckNamePolicyResult.Success -> Unit 39 | } 40 | } 41 | 42 | return when (val updateResult = petStore.updatePet(pet.id, petUpdate)) { 43 | UpdatePetResult.IllegalUpdate -> UpdatePetDetailsResult.InvalidUpdate 44 | UpdatePetResult.NotFound -> UpdatePetDetailsResult.PetNotFound 45 | is UpdatePetResult.Updated -> UpdatePetDetailsResult.Success(updateResult.pet) 46 | } 47 | } 48 | 49 | private fun checkNamePolicy(name: String): CheckNamePolicyResult = 50 | if (name.isNotBlank()) CheckNamePolicyResult.Success else CheckNamePolicyResult.Failure 51 | 52 | sealed class CheckNamePolicyResult { 53 | object Success : CheckNamePolicyResult() 54 | object Failure : CheckNamePolicyResult() 55 | } 56 | 57 | sealed class UpdatePetDetailsResult { 58 | data class Success(val pet: Pet) : UpdatePetDetailsResult() 59 | object OwnerNotFound : UpdatePetDetailsResult() 60 | object PetNotFound : UpdatePetDetailsResult() 61 | object MicrochipNotFound : UpdatePetDetailsResult() 62 | object InvalidMicrochip : UpdatePetDetailsResult() 63 | object OwnerMismatch : UpdatePetDetailsResult() 64 | object InvalidUpdate : UpdatePetDetailsResult() 65 | } 66 | 67 | interface MicrochipStore { 68 | suspend fun getMicrochip(microchipId: MicrochipId): Microchip? 69 | } 70 | 71 | interface PetOwnerStore { 72 | suspend fun getPetOwner(petOwnerId: PetOwnerId): PetOwner? 73 | } 74 | 75 | interface PetStore { 76 | suspend fun getPet(petId: PetId): Pet? 77 | suspend fun updatePet(petId: PetId, petUpdate: PetUpdate): UpdatePetResult 78 | } 79 | 80 | data class PetUpdate( 81 | val microchipId: MicrochipId? = null, 82 | val name: String? = null, 83 | val birthDate: LocalDate? = null, 84 | val petType: PetType? = null, 85 | val breed: String? = null, 86 | val gender: PetGender? = null 87 | ) 88 | 89 | sealed class UpdatePetResult { 90 | data class Updated(val pet: Pet) : UpdatePetResult() 91 | object NotFound : UpdatePetResult() 92 | object IllegalUpdate : UpdatePetResult() 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/myuwono/petshop/requirement7/SealedClassPetService.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop.requirement7 2 | 3 | import io.github.myuwono.petshop.Microchip 4 | import io.github.myuwono.petshop.MicrochipId 5 | import io.github.myuwono.petshop.Pet 6 | import io.github.myuwono.petshop.PetGender 7 | import io.github.myuwono.petshop.PetId 8 | import io.github.myuwono.petshop.PetOwner 9 | import io.github.myuwono.petshop.PetOwnerId 10 | import io.github.myuwono.petshop.PetType 11 | import java.time.LocalDate 12 | 13 | class SealedClassPetService( 14 | private val microchipStore: MicrochipStore, 15 | private val petStore: PetStore, 16 | private val petOwnerStore: PetOwnerStore 17 | ) { 18 | suspend fun updatePetDetails( 19 | petId: PetId, 20 | petOwnerId: PetOwnerId, 21 | petUpdate: PetUpdate 22 | ): UpdatePetDetailsResult { 23 | val pet = petStore.getPet(petId) 24 | return if (pet == null) { 25 | UpdatePetDetailsResult.PetNotFound 26 | } else { 27 | val owner = petOwnerStore.getPetOwner(petOwnerId) 28 | if (owner == null) { 29 | UpdatePetDetailsResult.OwnerNotFound 30 | } else { 31 | val microchip = microchipStore.getMicrochip(pet.microchipId) 32 | if (microchip == null) { 33 | UpdatePetDetailsResult.MicrochipNotFound 34 | } else { 35 | if (microchip.petId != pet.id) { 36 | UpdatePetDetailsResult.InvalidMicrochip 37 | } else { 38 | if (microchip.petOwnerId != owner.id) { 39 | UpdatePetDetailsResult.OwnerMismatch 40 | } else { 41 | val checkNamePolicyResult = petUpdate.name 42 | ?.let { checkNamePolicy(it) } 43 | ?: CheckNamePolicyResult.Success 44 | 45 | when (checkNamePolicyResult) { 46 | CheckNamePolicyResult.Failure -> UpdatePetDetailsResult.InvalidUpdate 47 | CheckNamePolicyResult.Success -> when (val updateResult = petStore.updatePet(pet.id, petUpdate)) { 48 | UpdatePetResult.IllegalUpdate -> UpdatePetDetailsResult.InvalidUpdate 49 | UpdatePetResult.NotFound -> UpdatePetDetailsResult.PetNotFound 50 | is UpdatePetResult.Updated -> UpdatePetDetailsResult.Success(updateResult.pet) 51 | } 52 | } 53 | } 54 | } 55 | } 56 | } 57 | } 58 | } 59 | 60 | private fun checkNamePolicy(name: String): CheckNamePolicyResult = 61 | if (name.isNotBlank()) CheckNamePolicyResult.Success else CheckNamePolicyResult.Failure 62 | 63 | sealed class CheckNamePolicyResult { 64 | object Success : CheckNamePolicyResult() 65 | object Failure : CheckNamePolicyResult() 66 | } 67 | 68 | sealed class UpdatePetDetailsResult { 69 | data class Success(val pet: Pet) : UpdatePetDetailsResult() 70 | object OwnerNotFound : UpdatePetDetailsResult() 71 | object PetNotFound : UpdatePetDetailsResult() 72 | object MicrochipNotFound : UpdatePetDetailsResult() 73 | object InvalidMicrochip : UpdatePetDetailsResult() 74 | object OwnerMismatch : UpdatePetDetailsResult() 75 | object InvalidUpdate : UpdatePetDetailsResult() 76 | } 77 | 78 | interface MicrochipStore { 79 | suspend fun getMicrochip(microchipId: MicrochipId): Microchip? 80 | } 81 | 82 | interface PetOwnerStore { 83 | suspend fun getPetOwner(petOwnerId: PetOwnerId): PetOwner? 84 | } 85 | 86 | interface PetStore { 87 | suspend fun getPet(petId: PetId): Pet? 88 | suspend fun updatePet(petId: PetId, petUpdate: PetUpdate): UpdatePetResult 89 | } 90 | 91 | data class PetUpdate( 92 | val microchipId: MicrochipId? = null, 93 | val name: String? = null, 94 | val birthDate: LocalDate? = null, 95 | val petType: PetType? = null, 96 | val breed: String? = null, 97 | val gender: PetGender? = null 98 | ) 99 | 100 | sealed class UpdatePetResult { 101 | data class Updated(val pet: Pet) : UpdatePetResult() 102 | object NotFound : UpdatePetResult() 103 | object IllegalUpdate : UpdatePetResult() 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/myuwono/petshop/requirement7/TaggedTypesFlatMapPetService.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop.requirement7 2 | 3 | import arrow.core.Either 4 | import arrow.core.Option 5 | import arrow.core.flatMap 6 | import arrow.core.getOrElse 7 | import arrow.core.left 8 | import arrow.core.none 9 | import arrow.core.right 10 | import io.github.myuwono.petshop.Microchip 11 | import io.github.myuwono.petshop.MicrochipId 12 | import io.github.myuwono.petshop.Pet 13 | import io.github.myuwono.petshop.PetGender 14 | import io.github.myuwono.petshop.PetId 15 | import io.github.myuwono.petshop.PetOwner 16 | import io.github.myuwono.petshop.PetOwnerId 17 | import io.github.myuwono.petshop.PetType 18 | import java.time.LocalDate 19 | 20 | class TaggedTypesFlatMapPetService( 21 | private val microchipStore: MicrochipStore, 22 | private val petStore: PetStore, 23 | private val petOwnerStore: PetOwnerStore 24 | ) { 25 | suspend fun updatePetDetails( 26 | petId: PetId, 27 | petOwnerId: PetOwnerId, 28 | petUpdate: PetUpdate 29 | ): Either = 30 | petStore.getPet(petId) 31 | .toEither { UpdatePetDetailsFailure.PetNotFound } 32 | .flatMap { pet -> 33 | petOwnerStore.getPetOwner(petOwnerId) 34 | .toEither { UpdatePetDetailsFailure.OwnerNotFound } 35 | .flatMap { owner -> 36 | microchipStore.getMicrochip(pet.microchipId) 37 | .toEither { UpdatePetDetailsFailure.MicrochipNotFound } 38 | .flatMap { microchip -> 39 | run { if (microchip.petId == pet.id) Unit.right() else UpdatePetDetailsFailure.InvalidMicrochip.left() } 40 | .flatMap { if (microchip.petOwnerId == owner.id) Unit.right() else UpdatePetDetailsFailure.OwnerMismatch.left() } 41 | .flatMap { petUpdate.name.map { checkNamePolicy(it) }.getOrElse { Unit.right() } } 42 | .flatMap { 43 | petStore.updatePet(pet.id, petUpdate).mapLeft { updatePetFailure -> 44 | when (updatePetFailure) { 45 | UpdatePetFailure.IllegalUpdate -> UpdatePetDetailsFailure.InvalidUpdate 46 | UpdatePetFailure.NotFound -> UpdatePetDetailsFailure.PetNotFound 47 | } 48 | } 49 | } 50 | } 51 | } 52 | } 53 | 54 | private fun checkNamePolicy(name: String): Either = 55 | if (name.isNotBlank()) Unit.right() else UpdatePetDetailsFailure.InvalidUpdate.left() 56 | 57 | interface MicrochipStore { 58 | suspend fun getMicrochip(microchipId: MicrochipId): Option 59 | } 60 | 61 | interface PetOwnerStore { 62 | suspend fun getPetOwner(petOwnerId: PetOwnerId): Option 63 | } 64 | 65 | interface PetStore { 66 | suspend fun getPet(petId: PetId): Option 67 | suspend fun updatePet(petId: PetId, petUpdate: PetUpdate): Either 68 | } 69 | 70 | data class PetUpdate( 71 | val microchipId: Option = none(), 72 | val name: Option = none(), 73 | val birthDate: Option = none(), 74 | val petType: Option = none(), 75 | val breed: Option = none(), 76 | val gender: Option = none() 77 | ) 78 | 79 | sealed class UpdatePetFailure { 80 | object NotFound : UpdatePetFailure() 81 | object IllegalUpdate : UpdatePetFailure() 82 | } 83 | 84 | sealed class UpdatePetDetailsFailure { 85 | object OwnerNotFound : UpdatePetDetailsFailure() 86 | object PetNotFound : UpdatePetDetailsFailure() 87 | object MicrochipNotFound : UpdatePetDetailsFailure() 88 | object InvalidMicrochip : UpdatePetDetailsFailure() 89 | object OwnerMismatch : UpdatePetDetailsFailure() 90 | object InvalidUpdate : UpdatePetDetailsFailure() 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/kotlin/io/github/myuwono/petshop/requirement7/TaggedTypesPetService.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop.requirement7 2 | 3 | import arrow.core.Either 4 | import arrow.core.raise.either 5 | import arrow.core.raise.ensure 6 | import arrow.core.raise.recover 7 | import io.github.myuwono.petshop.Microchip 8 | import io.github.myuwono.petshop.MicrochipId 9 | import io.github.myuwono.petshop.Pet 10 | import io.github.myuwono.petshop.PetGender 11 | import io.github.myuwono.petshop.PetId 12 | import io.github.myuwono.petshop.PetOwner 13 | import io.github.myuwono.petshop.PetOwnerId 14 | import io.github.myuwono.petshop.PetType 15 | import java.time.LocalDate 16 | 17 | class TaggedTypesPetService( 18 | private val microchipStore: MicrochipStore, 19 | private val petStore: PetStore, 20 | private val petOwnerStore: PetOwnerStore 21 | ) { 22 | suspend fun updatePetDetails( 23 | petId: PetId, 24 | petOwnerId: PetOwnerId, 25 | petUpdate: PetUpdate 26 | ): Either = either { 27 | val pet = petStore.getPet(petId) ?: raise(UpdatePetDetailsFailure.PetNotFound) 28 | val owner = petOwnerStore.getPetOwner(petOwnerId) ?: raise(UpdatePetDetailsFailure.OwnerNotFound) 29 | val microchip = microchipStore.getMicrochip(pet.microchipId) ?: raise(UpdatePetDetailsFailure.MicrochipNotFound) 30 | 31 | ensure(microchip.petId == pet.id) { UpdatePetDetailsFailure.InvalidMicrochip } 32 | ensure(microchip.petOwnerId == owner.id) { UpdatePetDetailsFailure.OwnerMismatch } 33 | 34 | petUpdate.name?.let { checkNamePolicy(it).bind() } 35 | 36 | recover({ petStore.updatePet(pet.id, petUpdate).bind() }) { updatePetFailure -> 37 | when (updatePetFailure) { 38 | UpdatePetFailure.IllegalUpdate -> raise(UpdatePetDetailsFailure.InvalidUpdate) 39 | UpdatePetFailure.NotFound -> raise(UpdatePetDetailsFailure.PetNotFound) 40 | } 41 | } 42 | } 43 | 44 | private fun checkNamePolicy(name: String): Either = either { 45 | ensure(name.isNotBlank()) { 46 | UpdatePetDetailsFailure.InvalidUpdate 47 | } 48 | } 49 | 50 | interface MicrochipStore { 51 | suspend fun getMicrochip(microchipId: MicrochipId): Microchip? 52 | } 53 | 54 | interface PetOwnerStore { 55 | suspend fun getPetOwner(petOwnerId: PetOwnerId): PetOwner? 56 | } 57 | 58 | interface PetStore { 59 | suspend fun getPet(petId: PetId): Pet? 60 | suspend fun updatePet(petId: PetId, petUpdate: PetUpdate): Either 61 | } 62 | 63 | data class PetUpdate( 64 | val microchipId: MicrochipId? = null, 65 | val name: String? = null, 66 | val birthDate: LocalDate? = null, 67 | val petType: PetType? = null, 68 | val breed: String? = null, 69 | val gender: PetGender? = null 70 | ) 71 | 72 | sealed class UpdatePetFailure { 73 | object NotFound : UpdatePetFailure() 74 | object IllegalUpdate : UpdatePetFailure() 75 | } 76 | 77 | sealed class UpdatePetDetailsFailure { 78 | object OwnerNotFound : UpdatePetDetailsFailure() 79 | object PetNotFound : UpdatePetDetailsFailure() 80 | object MicrochipNotFound : UpdatePetDetailsFailure() 81 | object InvalidMicrochip : UpdatePetDetailsFailure() 82 | object OwnerMismatch : UpdatePetDetailsFailure() 83 | object InvalidUpdate : UpdatePetDetailsFailure() 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/kotlin/io/github/myuwono/petshop/Level1Test.kt: -------------------------------------------------------------------------------- 1 | package io.github.myuwono.petshop 2 | 3 | import io.kotest.core.spec.style.FunSpec 4 | import io.kotest.matchers.shouldBe 5 | 6 | class Level1Test : FunSpec() { 7 | init { 8 | test("should be ok") { 9 | "foo" shouldBe "foo" 10 | } 11 | } 12 | } 13 | --------------------------------------------------------------------------------