Slide 1

Slide 1 text

Ragunath Jawahar @ragunathjawahar https://ragunath.xyz Building Robust Software Episode 2: Exceptions, side-e ff ects and boundaries

Slide 2

Slide 2 text

Why? • People • Code • Process • Tooling

Slide 3

Slide 3 text

Why? • People • Code • Process • Tooling

Slide 4

Slide 4 text

Code • Less bureaucracy • Simple ideas • Starting point to hone your craft

Slide 5

Slide 5 text

Recap • Robustness principle + tweaked version • Algebraic data types with Kotlin’s sealed classes • Total & partial functions • Using types, • To prevent defensive programming overhead • To avoid primitive obsession

Slide 6

Slide 6 text

Episode 1 https://bit.ly/30zwgTy

Slide 7

Slide 7 text

Pendulum swings

Slide 8

Slide 8 text

// Primitive obsession val password: String = "super secret stuff!" PasswordValidator.validate(password) // Encapsulated type val password: Password = Password("super secret stuff!") password.validate(password)

Slide 9

Slide 9 text

// Primitive obsession val password: String = "super secret stuff!" PasswordValidator.validate(password) // Encapsulated type val password: Password = Password("super secret stuff!") password.validate(password)

Slide 10

Slide 10 text

// Primitive obsession val password: String = "super secret stuff!" PasswordValidator.validate(password) // Encapsulated type val password: Password = Password("super secret stuff!") password.validate(password)

Slide 11

Slide 11 text

// Primitive obsession val password: String = "super secret stuff!" PasswordValidator.validate(password) // Encapsulated type val password: Password = Password("super secret stuff!") password.validate(password)

Slide 12

Slide 12 text

Pendulum swings example Primitive obsession • Built-in operators (+, -, !, & & , || , [], etc.,) • value or inline classes • ORM and serialisation/deserialisation libraries • Don’t have enough clarity about the problem domain

Slide 13

Slide 13 text

Exceptions

Slide 14

Slide 14 text

https://docs.oracle.com/javase/tutorial/essential/exceptions/de fi nition.html The term exception is shorthand for the phrase “exceptional event.”

Slide 15

Slide 15 text

Treat exceptions as first class citizens.

Slide 16

Slide 16 text

Exceptions Anti-patterns

Slide 17

Slide 17 text

try { / / make a network call } catch (e: IOException) { / / Gulp !! 🥤 } catch (e: HttpRetryException) { / / Delicious 😋 } 1. Swallowing exceptions

Slide 18

Slide 18 text

try { / / make a network call } catch (e: Exception) { showSomethingWentWrong() } 2. Catch-all

Slide 19

Slide 19 text

private fun isNumber(candidate: String): Boolean { return try { Integer.parseInt(candidate) true } catch (e: NumberFormatException) { false } } 3. Using exceptions for control flow

Slide 20

Slide 20 text

… Result "xyz.ragunath.benchmark.ReturnValues.returnValueTest": 224747599.794 ±(99.9%) 1251327.222 ops/s [Average] (min, avg, max) = (220755995.007, 224747599.794, 227672182.229), stdev = 1670486.041 CI (99.9%): [223496272.572, 225998927.016] (assumes normal distribution) … Result "xyz.ragunath.benchmark.StackTraces.stackTraceTest": 5830.292 ±(99.9%) 31.441 ops/s [Average] (min, avg, max) = (5676.655, 5830.292, 5889.489), stdev = 41.973 CI (99.9%): [5798.851, 5861.733] (assumes normal distribution) …

Slide 21

Slide 21 text

… Result "xyz.ragunath.benchmark.ReturnValues.returnValueTest": 224747599.794 ±(99.9%) 1251327.222 ops/s [Average] (min, avg, max) = (220755995.007, 224747599.794, 227672182.229), stdev = 1670486.041 CI (99.9%): [223496272.572, 225998927.016] (assumes normal distribution) … Result "xyz.ragunath.benchmark.StackTraces.stackTraceTest": 5830.292 ±(99.9%) 31.441 ops/s [Average] (min, avg, max) = (5676.655, 5830.292, 5889.489), stdev = 41.973 CI (99.9%): [5798.851, 5861.733] (assumes normal distribution) …

Slide 22

Slide 22 text

… Result "xyz.ragunath.benchmark.ReturnValues.returnValueTest": 224747599.794 ±(99.9%) 1251327.222 ops/s [Average] (min, avg, max) = (220755995.007, 224747599.794, 227672182.229), stdev = 1670486.041 CI (99.9%): [223496272.572, 225998927.016] (assumes normal distribution) … Result "xyz.ragunath.benchmark.StackTraces.stackTraceTest": 5830.292 ±(99.9%) 31.441 ops/s [Average] (min, avg, max) = (5676.655, 5830.292, 5889.489), stdev = 41.973 CI (99.9%): [5798.851, 5861.733] (assumes normal distribution) …

Slide 23

Slide 23 text

… Result "xyz.ragunath.benchmark.ReturnValues.returnValueTest": 224747599.794 ±(99.9%) 1251327.222 ops/s [Average] (min, avg, max) = (220755995.007, 224747599.794, 227672182.229), stdev = 1670486.041 CI (99.9%): [223496272.572, 225998927.016] (assumes normal distribution) … Result "xyz.ragunath.benchmark.StackTraces.stackTraceTest": 5830.292 ±(99.9%) 31.441 ops/s [Average] (min, avg, max) = (5676.655, 5830.292, 5889.489), stdev = 41.973 CI (99.9%): [5798.851, 5861.733] (assumes normal distribution) …

Slide 24

Slide 24 text

… Result "xyz.ragunath.benchmark.ReturnValues.returnValueTest": 224747599.794 ±(99.9%) 1251327.222 ops/s [Average] (min, avg, max) = (220755995.007, 224747599.794, 227672182.229), stdev = 1670486.041 CI (99.9%): [223496272.572, 225998927.016] (assumes normal distribution) … Result "xyz.ragunath.benchmark.StackTraces.stackTraceTest": 5830.292 ±(99.9%) 31.441 ops/s [Average] (min, avg, max) = (5676.655, 5830.292, 5889.489), stdev = 41.973 CI (99.9%): [5798.851, 5861.733] (assumes normal distribution) …

Slide 25

Slide 25 text

… Result "xyz.ragunath.benchmark.ReturnValues.returnValueTest": 224747599.794 ±(99.9%) 1251327.222 ops/s [Average] (min, avg, max) = (220755995.007, 224747599.794, 227672182.229), stdev = 1670486.041 CI (99.9%): [223496272.572, 225998927.016] (assumes normal distribution) … Result "xyz.ragunath.benchmark.StackTraces.stackTraceTest": 5830.292 ±(99.9%) 31.441 ops/s [Average] (min, avg, max) = (5676.655, 5830.292, 5889.489), stdev = 41.973 CI (99.9%): [5798.851, 5861.733] (assumes normal distribution) …

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

for (candidate in potentialNumbers) { if (isNumber(candidate)) { println("It's a number!") } else { println("NaN") } } 3. Using exceptions for control flow (contd…)

Slide 28

Slide 28 text

Tests

Slide 29

Slide 29 text

assertThat(false).isTrue() Tests

Slide 30

Slide 30 text

Exception in thread "main" expected to be true at CanaryTestKt.main(CanaryTest.kt:15) at CanaryTestKt.main(CanaryTest.kt) Tests

Slide 31

Slide 31 text

if (balance < requestedAmount) { throw Exception("Meh… 😒") } 4. Throwing Exception

Slide 32

Slide 32 text

Exception handling in Kotlin • No checked exceptions • try is an expression

Slide 33

Slide 33 text

var guardDogResult: Result try { guardDogResult = getGuardDog() } catch (e: NoGuardDogException) { guardDogResult = Result.failure(e) } try expression

Slide 34

Slide 34 text

val guardDogResult: Result = try { getGuardDog() } catch (e: NoGuardDogException) { Result.failure(e) } try expression

Slide 35

Slide 35 text

Exception handling patterns

Slide 36

Slide 36 text

1. Tester-Doer pattern • Tester - a member that is used to test a condition • Doer - a member that performs a potentially throwing operation

Slide 37

Slide 37 text

stack.pop()

Slide 38

Slide 38 text

java.util.EmptyStackException at java.base/java.util.Stack.peek(Stack.java:102) at java.base/java.util.Stack.pop(Stack.java:84) at MainKt.main(Main.kt:8) at MainKt.main(Main.kt)

Slide 39

Slide 39 text

if (stack.isNotEmpty()) { stack.pop() }

Slide 40

Slide 40 text

2. Try-Parse pattern • Unvalidated input data • tryParse - veri fi es if the input is valid and can be parsed • parse - performs the actual parsing

Slide 41

Slide 41 text

if (SerialNumber.tryParse(possiblySerialNumber)) { val serialNumber = SerialNumber.parse(possiblySerialNumber) save(serialNumber) }

Slide 42

Slide 42 text

3. Converting exceptions to values • Non-trivial exceptional conditions • Exception has domain meaning • Has to be communicated to the consumer • Use Kotlin’s sealed classes, data classes and object to provide meaning

Slide 43

Slide 43 text

Registering a new user from a client • Successfully creates a user account • Email already registered • Validation errors • Connection errors • 5xx server errors • Unknown errors

Slide 44

Slide 44 text

Registering a new user from a client • Successfully creates a user account • Email already registered • Validation errors • Connection errors • 5xx server errors • Unknown errors

Slide 45

Slide 45 text

SignupResponse.kt sealed class SignupResponse { data class AccountCreated(val userId: String) : SignupResponse() data class EmailAlreadyRegistered(val registrationEmail: String) : SignupResponse() data class InputValidationFailed(val errors: List) : SignupResponse() object ConnectionError : SignupResponse() data class ServerError(val statusCode: Int) : SignupResponse() data class UnknownError(val statusCode: Int, val responseBody: String?) : SignupResponse() }

Slide 46

Slide 46 text

Usage 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() }

Slide 47

Slide 47 text

Exceptions summary • Exception handling summary • Kotlin’s try expression • Tester-Doer pattern • Try-Parse pattern • Converting exceptions to values

Slide 48

Slide 48 text

Boundaries

Slide 49

Slide 49 text

Objective • Find attendees that have RSVP’d “Yes” or “Maybe” • Remind them about an upcoming event

Slide 50

Slide 50 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 51

Slide 51 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 52

Slide 52 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 53

Slide 53 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 54

Slide 54 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 55

Slide 55 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 56

Slide 56 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 57

Slide 57 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 58

Slide 58 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 59

Slide 59 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 60

Slide 60 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } }

Slide 61

Slide 61 text

Values as boundaries

Slide 62

Slide 62 text

fun List.attending(): List { return filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } }

Slide 63

Slide 63 text

fun List.attending(): List { return filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } }

Slide 64

Slide 64 text

fun List.attending(): List { return filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } }

Slide 65

Slide 65 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 66

Slide 66 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 67

Slide 67 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 68

Slide 68 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 69

Slide 69 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 70

Slide 70 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 71

Slide 71 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 72

Slide 72 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 73

Slide 73 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 74

Slide 74 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 75

Slide 75 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 76

Slide 76 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } }

Slide 77

Slide 77 text

Testing (Isolated for logic & Integrated for effects) • No attendees • All RSVP’d “Yes” • All RSVP’d “No” • All RSVP’d “Maybe” • Mix of “Yes”, “No”, “Maybe” • Query database, Send email

Slide 78

Slide 78 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { val attendees = dao.getAttendees() val potentialAttendees = attendees .filter { it.rsvp == Rsvp.YES | | it.rsvp == Rsvp.MAYBE } potentialAttendees .onEach { mailer.mail(it) } } } Testing 😱

Slide 79

Slide 79 text

Testing (Isolated for logic & Integrated for effects) • No attendees • All RSVP’d “Yes” • All RSVP’d “No” • All RSVP’d “Maybe” • Mix of “Yes”, “No”, “Maybe” • Query database, Send email

Slide 80

Slide 80 text

class EventManager( private val dao: EventDao, private val mailer: EventMailer ) { fun sendReminder() { dao.getAttendees() .attending() .onEach { mailer.mail(it) } } } Testing 🥳

Slide 81

Slide 81 text

Core • Path + • Dependencies - • Isolated tests Shell • Path - • Dependencies + • Integrated tests

Slide 82

Slide 82 text

https://github.com/redgreenio/ fl uid

Slide 83

Slide 83 text

Value as boundaries in the wild • HTTP • IPC • RPC • Actor-based systems • Event-driven systems • Message queues • Event streams

Slide 84

Slide 84 text

Architectures • Functional core & imperative shell • Hexagonal architecture • Ports & adapters • Redux

Slide 85

Slide 85 text

References • https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html • https://kotlinlang.org/docs/exceptions.html • https://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html • https://www.artima.com/articles/the-trouble-with-checked-exceptions • https://www.destroyallsoftware.com/talks/boundaries • https://github.com/spotify/mobius • https://github.com/redgreenio/fluid

Slide 86

Slide 86 text

Questions? @ragunathjawahar • https: / / ragunath.xyz