Domain Model Validation In Kotlin: Part 2

Don’t fail fast; fail comprehensively

source: pxfuel

Validating multiple properties and accumulating errors

  • (6) both from and to are valid so that we can construct an EmailRoute; from and to are Valid<Email>
  • (7)(8) only one of the values is invalid, we return the invalid one directly; Invalid<E> has a single type param, and it can substitute both Validated<ValidationErrors, Email> and Validated<ValidationErrors, EmailRoute>
  • (9) both emails are invalid, therefore we have to concatenate the errors

Validating lists of elements

Validation rules that depend on multiple properties

  • the first one is a function to map the errors — we rewrap the errors in an Invalid (I used function reference ValidationErrors::invalid because two lambda parameters don’t look very natural)
  • the second one is a function to map valid values — and here we’re adding extra conditions transforming if needed our valid value into an invalid one

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store