Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Easy and Efficient Data Validation with Cats

Easy and Efficient Data Validation with Cats

Often when we create a client/server application, we need to validate the requests: can the user associated to the request perform this operation? Can they access or modify the data? Is the input well-formed?

When the data validation component in our application is not well designed, the code can quickly become not expressive enough and probably difficult to maintain. Business rules don't help, adding more and more requirements to add in our validation, making it more and more complex to clearly represent and maintain. At the same time when the validation fails, it should be fairly straight forward to understand why the request was rejected, so that actions can be taken accordingly.

This talk introduces Cats, a Scala library based on category theory, and some of its most interesting components for data validation. In particular we'll discuss some options to achieve efficient and expressive data validation. We will also argue that, compared to other options in the language, Cats is particularly suited for the task thanks to its easy-to-use data types and more approachable syntax.

Throughout the talk, you will see numerous examples on how data validation can be achieved in a clean and robust way, and how we can easily integrate it in our code, without any specific knowledge of category theory.

Daniela Sfregola

October 27, 2016
Tweet

More Decks by Daniela Sfregola

Other Decks in Programming

Transcript

  1. DATA VALIDATION > In almost every application > Can be

    come complex quite quickly > Needs to be maintained
  2. MAP scala> Some("daniela").map(s => "yo " + s) res0: Option[String]

    = Some(yo daniela) scala> None.map(s => "yo " + s) res1: Option[String] = None
  3. FLATMAP map + flatten scala> Some("daniela").flatMap(s => Some("yo " +

    s)) res2: Option[String] = Some(yo daniela) scala> None.flatMap(s => Some("yo " + s)) res3: Option[String] = None
  4. FOR-COMPREHENSION map + flatMap + filter scala > for {

    a <- Some(1); b <- Some(5) } yield a + b res4: Option[Int] = Some(6) scala > for { a <- Some(1); b <- None } yield a + b res5: Option[Int] = None
  5. OPTION package scala sealed abstract class Option[+A] final case class

    Some[+A](x: A) extends Option[A] case object None extends Option[Nothing] def map[B](f: A => B): Option[B] = ??? def flatMap[B](f: A => Option[B]): Option[B] = ???
  6. OPTION case class Data(email: String, phone: String) def validateEmail(e: String):

    Option[String] = ??? def validatePhone(p: String): Option[String] = ??? def validateData(d: Data): Option[Data] = for { validEmail <- validateEmail(d.email) validPhone <- validatePhone(d.phone) } yield Data(validEmail, validPhone)
  7. EITHER package scala.util sealed abstract class Either[+A, +B] final case

    class Left[+A, +B](a: A) extends Either[A, B] final case class Right[+A, +B](b: B) extends Either[A, B] // no map // no flatMap
  8. EITHER package scala.util final case class LeftProjection[+A, +B](e: Either[A, B])

    final case class RightProjection[+A, +B](e: Either[A, B]) /** * Right(12).left.map(x => "flower") // Result: Right(12) * Left(12).left.map(x => "flower") // Result: Left("flower") * * Right(12).right.map(x => "flower") // Result: Right("flower") * Left(12).right.map(x => "flower") // Result: Left(12) **/ // same for flatmap!
  9. EITHER case class Data(email: String, phone: String) def validateEmail(e: String):

    Either[List[String], String] = ??? def validatePhone(p: String): Either[List[String], String] = ??? def validateData(d: Data): Either[List[String], Data] = { val validEmail = validateEmail(d.email) val validPhone = validatePhone(d.phone) (validEmail, validPhone) match { case (Right(e), Right(p)) => Right(Data(e, p)) case (Left(errE), Left(errP)) => Left(errE ++ errP) case (Left(errE), _) => Left(errE) case (_, Left(errP)) => Left(errP) } }
  10. EITHER Which one is the error? Which one is the

    valid value? Either is not biased* *things have changed in Scala 2.12
  11. XOR package cats.data sealed abstract class Xor[+A, +B] final case

    class Left[+A](a: A) extends (A Xor Nothing) final case class Right[+B](b: B) extends (Nothing Xor B) def map[D](f: B => D): A Xor D = ??? def flatMap[AA >: A, D](f: B => AA Xor D): AA Xor D = ???
  12. XOR import cats.data.Xor case class Data(email: String, phone: String) def

    validateEmail(e: String): Xor[List[String], String] = ??? def validatePhone(p: String): Xor[List[String], String] = ??? def validateData(d: Data): Xor[List[String], Data] = for { validEmail <- validateEmail(d.email) validPhone <- validatePhone(d.phone) } yield Data(validEmail, validPhone)
  13. XOR* > only one validation is performed > ideal only

    when error accumulation is not needed * Removed from Cats 0.8.0!
  14. VALIDATED package cats.data sealed abstract class Validated[+E, +A] final case

    class Valid[+A](a: A) extends Validated[Nothing, A] final case class Invalid[+E](e: E) extends Validated[E, Nothing] def map[B](f: A => B): Validated[E,B] // no flatmap //...but we have something else *really* useful!
  15. VALIDATED AND APPLY* import cats.Apply import cats.data.Validated def accumulate[E, A1,

    A2, B](v1: Validated[E, A1], v2: Validated[E, A2])(f: (A1, A2) => B): Validated[E, B] = Apply[Validated[E, ?]].map2(v1,v2)(f) or alternatively import cats.implicits._ import cats.data.Validated def accumulate[E, A1, A2, B](v1: Validated[E, A1], v2: Validated[E, A2])(f: (A1, A2) => B): Validated[E, B] = (v1 |@| v2).map(f) * More info on Apply at http://typelevel.org/cats/typeclasses/apply.html
  16. VALIDATED import cats.implicits._ import cats.data.Validated case class Data(email: String, phone:

    String) def validateEmail(e: String): Validated[List[String], String] = ??? def validatePhone(p: String): Validated[List[String], String] = ??? def validateData(d: Data): Validated[List[String], Data] = { val validEmail = validateEmail(d.email) val validPhone = validatePhone(d.phone) (validEmail |@| validPhone).map(Data) }
  17. USE AN EXPRESSIVE ERROR TYPE object ErrorCode extends Enumeration {

    type ErrorCode = Value val InvalidEmailFormat, ..., PhoneMustBeNumeric = Value } import ErrorCode._ case class Err(code: ErrorCode, msg: String)
  18. OUR FINAL SOLUTION import cats.data._ import cats.implicits._ case class Data(email:

    String, phone: String) def validateEmail(e: String): ValidatedNel[Err, String] = ??? def validatePhone(p: String): ValidatedNel[Err, String] = ??? def validateData(d: Data): ValidatedNel[Err, Data] = { val validEmail = validateEmail(d.email) val validPhone = validatePhone(d.phone) validEmail |@| validPhone map (Data) }
  19. STEP 1 > Pick an error representation > stick to

    it! case class Err(code: ErrorCode, msg: String)
  20. A CONCRETE EXAMPLE sealed trait Err { val code: String

    val msg: String val values: Seq[AnyRef] } case class BadRequest(code: String, msg: String) extends Err { val values = Seq.empty } case class NotFound(code: String, msg: String, values: Seq[AnyRef]) extends Err
  21. A CONCRETE EXAMPLE type Validation[T] = ValidatedNel[Err, T] import cats.data._

    object Validation extends AccumulateArities { def success[T](t: T): Validation[T] = Validated.valid(t) def failure[T](e: Err): Validation[T] = Validated.invalidNel(e) }
  22. A CONCRETE EXAMPLE trait AccumulateArities { /** Accumulate function for

    Validation[T] of arity 2 */ def accumulate[T1,T2,Z](v1: Validation[T1], v2: Validation[T2]) (f: (T1,T2) => Z): Validation[Z] = Apply[Validation].map2(v1,v2)(f) /** Accumulate function for Validation[T] of arity 3 */ def accumulate[T1,T2,T3,Z](v1: Validation[T1], v2: Validation[T2], v3: Validation[T3]) (f: (T1,T2,T3) => Z): Validation[Z] = Apply[Validation].map3(v1,v2,v3)(f) // ...until arity 22! }
  23. SUMMARY > Do not reinvent the wheel > Choose an

    expressive type > Customise the solution to your needs