SlideShare a Scribd company logo
1 of 34
Download to read offline
From OOP to FP
✅ The Validation case
Emmanuel Nhan - JUG Montpellier 15 mai 2019
😡 😡 😡 🤬
Let’s see the code…
💡There gotta be a
better way ! 🤔
Sticking in Javaland ☕
• Standard is JSR 303 : Bean Validation

• Let’s give it a try: Fortunately it is built-in in Spring !
In Action 🛠
JSR 303 results : the good
( Accumulates the errors for us in : 

Set<ConstraintViolation<… >>
( Automatic 400 Bad Requests (although this is mostly
done by Spring)

( Support for basic use cases
JSR 303 results : the bad
) No support for the parse error of HostAndPort

) Need custom handling for inter-dependent fields

) Annotations are not type-checked

) Weird mix of custom/covered cases

) Smelling reflection down there…
JSR 303 results : the weirdo
🤔 Automatic translation of error messages
Why is presentation even related to Validation ???

*
💡There gotta be a
better way ! 🤔
(Again !!!)
Do It Yourself 🛠
Let’s go back to the essence of our problem…
Validating one
• Result of a validation is either an error or a value

• Validation is just the function producing that result

• It looks like Optional structure but with an error type 

• We need a way to use the validated result
Validated ✅ (Kotlin style)
sealed class Validated<E, V> {
data class Valid<E,V>(val value: V) :
Validated<E,V>()
data class Invalid<E, V>(val error: E):
Validated<E, V>()
}
So far…
We can :

• create a validated with success with Valid(a)

• create a validated with error with Invalid(e)
• map over a Valid value
Representing errors
• Let’s use an ADT. In Kotlin :

sealed class AlertCreationError {
data class ThresholdATooLow( /* ... */):
AlertCreationError()
data class ThresholdCTooHigh( /* ... */):
AlertCreationError()
data class ThresholdBNotInBetween(
/* ... */): AlertCreationError()
// And so on
}
So far…
We can :

• create a validated with success with Valid(a)
• create a validated with error with Invalid(e)
• map over a Valid value

• fix the type of field validation to
Validated<AlertCreationError, T>
Validating many 🤔
• Finding a way to compose validation errors

• Finding a way to compose valid results
We need Composition !
Error Accumulation 📋
• JSR 303 used a Set

• When in error, we will at least have one element

• Let’s add some precision
NonEmpty*
• Two types exists

• NonEmptyList (NEL)

• NonEmptyChain (NEC)

• Structures which looks like a linked list 

but which contains at least one element

• Ensuring this condition via smart constructor
Keeping Validated generic
• We need the E type in Validated<E, R> to be
combinable

• That is a function combine: (E, E) -> E
• In the jargon, it is called Semigroup

• We need to go from

Validated<E, R> to Validated<Nel<E>, R>
So far…
We can :

• create a validated with success with Valid(a)
• create a validated with error with Invalid(e)
• map over a Valid value

• fix the type of field validation to
Validated<AlertCreationError, T>
• lift the error type from E to Nel<E> (mapLeft)
Validating many
• Validating A is independent of validating B

• We need a function, with the shape :

(F<A>,F<B>,(A,B) -> C) -> F<C>
• Where F is a type like Validated with a fixed type

• In the jargon, this is called Applicative
So far…
We can :

• create a validated with success with Valid(a)
• create a validated with error with Invalid(e)
• map over a Valid value

• fix the type of field validation to
Validated<AlertCreationError, T>
• lift the error type from E to Nel<E> & accumulate errors

• Combine all values when all fields are in Valid state

• Keep invalid when at least one field is in Invalid state
Not really DIY
In Action 🛠 (Kotlin)
Take away 🥡🍜
Validation is an easy problem which can be solved with just
2 things :

✓Appropriate data structures (some may say ADT) to
model errors & to model validation results

✓An abstraction to express independent computations
(Applicative)
💡There gotta be a
better way ! 🤔
(Again & again !!!)
This is nice and all but…
Can we go further ? 🚀
• 💡We could try to make impossible states
unrepresentable

• There is this thing called Refined

• Let’s see some Scala… 

(sorry I’m not fluent in Haskell 🙊)
Refined in action
Not there yet ! 💫
• Clearly I’m not an expert (but if you are, let’s talk 🤩)

• Even for a simple case like Validation research is
important

• Mathematics are the (best) base tool at hand
Q&A time
Thanks for listening

@enhan on Github &
@nhanmanu on Twitter
References & credits
• Code: 

• https://github.com/enhan/oop-to-fp-validation

• https://github.com/enhan/refined-validation

• Articles: 

• https://typelevel.org/cats/datatypes/validated.html

• https://arrow-kt.io/docs/arrow/data/validated/

• https://www.enhan.eu/how-to-in-fp/
References & credits
• Books:

• Functional Programming in Scala (Paul Chiusano and
Runar Bjarnason)

• Category Theory for Programmers (Bartosz Milewski)
References & credits
• Libs:

• Spring: https://spring.io/

• Arrow: https://arrow-kt.io/

• Cats: https://typelevel.org/cats/

• Refined: https://github.com/fthomas/refined
References & credits
• Pictures (all from unsplash, in order) :

• SpaceX

• Anthony Cantin

• Mirko Blicke

• Simon Caspersen

• Alexey Sukhariev

• Designecologist

More Related Content

What's hot

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven DevelopmentKerry Buckley
 
Junit Recipes - Elementary tests (1/2)
Junit Recipes  - Elementary tests (1/2)Junit Recipes  - Elementary tests (1/2)
Junit Recipes - Elementary tests (1/2)Will Shen
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby evalNiranjan Sarade
 
Swift testing ftw
Swift testing ftwSwift testing ftw
Swift testing ftwJorge Ortiz
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 VariablesHock Leng PUAH
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#Raghu nath
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Logical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsLogical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsPVS-Studio
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeAmar Shah
 
Spf Chapter5 Conditional Logics
Spf Chapter5 Conditional LogicsSpf Chapter5 Conditional Logics
Spf Chapter5 Conditional LogicsHock Leng PUAH
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++Neeru Mittal
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
Decision statements
Decision statementsDecision statements
Decision statementsJaya Kumari
 

What's hot (20)

JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Behaviour-Driven Development
Behaviour-Driven DevelopmentBehaviour-Driven Development
Behaviour-Driven Development
 
Junit Recipes - Elementary tests (1/2)
Junit Recipes  - Elementary tests (1/2)Junit Recipes  - Elementary tests (1/2)
Junit Recipes - Elementary tests (1/2)
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby eval
 
Swift testing ftw
Swift testing ftwSwift testing ftw
Swift testing ftw
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 Variables
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Logical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsLogical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by Professionals
 
Mock with Mockito
Mock with MockitoMock with Mockito
Mock with Mockito
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Spf Chapter5 Conditional Logics
Spf Chapter5 Conditional LogicsSpf Chapter5 Conditional Logics
Spf Chapter5 Conditional Logics
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Presentation1
Presentation1Presentation1
Presentation1
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
Decision statements
Decision statementsDecision statements
Decision statements
 

Similar to From OOP to FP: The validation case

Similar to From OOP to FP: The validation case (20)

Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
DefensiveProgramming (1).pptx
DefensiveProgramming (1).pptxDefensiveProgramming (1).pptx
DefensiveProgramming (1).pptx
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle GamesWe Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
CPP10 - Debugging
CPP10 - DebuggingCPP10 - Debugging
CPP10 - Debugging
 
2600 Thailand #50 From 0day to CVE
2600 Thailand #50 From 0day to CVE2600 Thailand #50 From 0day to CVE
2600 Thailand #50 From 0day to CVE
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 

Recently uploaded

The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 

Recently uploaded (20)

The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 

From OOP to FP: The validation case

  • 1. From OOP to FP ✅ The Validation case Emmanuel Nhan - JUG Montpellier 15 mai 2019
  • 2. 😡 😡 😡 🤬 Let’s see the code…
  • 3. 💡There gotta be a better way ! 🤔
  • 4. Sticking in Javaland ☕ • Standard is JSR 303 : Bean Validation • Let’s give it a try: Fortunately it is built-in in Spring !
  • 6. JSR 303 results : the good ( Accumulates the errors for us in : Set<ConstraintViolation<… >> ( Automatic 400 Bad Requests (although this is mostly done by Spring) ( Support for basic use cases
  • 7. JSR 303 results : the bad ) No support for the parse error of HostAndPort ) Need custom handling for inter-dependent fields ) Annotations are not type-checked ) Weird mix of custom/covered cases ) Smelling reflection down there…
  • 8. JSR 303 results : the weirdo 🤔 Automatic translation of error messages Why is presentation even related to Validation ??? *
  • 9. 💡There gotta be a better way ! 🤔 (Again !!!)
  • 10. Do It Yourself 🛠 Let’s go back to the essence of our problem…
  • 11. Validating one • Result of a validation is either an error or a value • Validation is just the function producing that result • It looks like Optional structure but with an error type • We need a way to use the validated result
  • 12. Validated ✅ (Kotlin style) sealed class Validated<E, V> { data class Valid<E,V>(val value: V) : Validated<E,V>() data class Invalid<E, V>(val error: E): Validated<E, V>() }
  • 13. So far… We can : • create a validated with success with Valid(a) • create a validated with error with Invalid(e) • map over a Valid value
  • 14. Representing errors • Let’s use an ADT. In Kotlin : sealed class AlertCreationError { data class ThresholdATooLow( /* ... */): AlertCreationError() data class ThresholdCTooHigh( /* ... */): AlertCreationError() data class ThresholdBNotInBetween( /* ... */): AlertCreationError() // And so on }
  • 15. So far… We can : • create a validated with success with Valid(a) • create a validated with error with Invalid(e) • map over a Valid value • fix the type of field validation to Validated<AlertCreationError, T>
  • 16. Validating many 🤔 • Finding a way to compose validation errors • Finding a way to compose valid results We need Composition !
  • 17. Error Accumulation 📋 • JSR 303 used a Set • When in error, we will at least have one element • Let’s add some precision
  • 18. NonEmpty* • Two types exists • NonEmptyList (NEL) • NonEmptyChain (NEC) • Structures which looks like a linked list 
 but which contains at least one element • Ensuring this condition via smart constructor
  • 19. Keeping Validated generic • We need the E type in Validated<E, R> to be combinable • That is a function combine: (E, E) -> E • In the jargon, it is called Semigroup • We need to go from
 Validated<E, R> to Validated<Nel<E>, R>
  • 20. So far… We can : • create a validated with success with Valid(a) • create a validated with error with Invalid(e) • map over a Valid value • fix the type of field validation to Validated<AlertCreationError, T> • lift the error type from E to Nel<E> (mapLeft)
  • 21. Validating many • Validating A is independent of validating B • We need a function, with the shape : (F<A>,F<B>,(A,B) -> C) -> F<C> • Where F is a type like Validated with a fixed type • In the jargon, this is called Applicative
  • 22. So far… We can : • create a validated with success with Valid(a) • create a validated with error with Invalid(e) • map over a Valid value • fix the type of field validation to Validated<AlertCreationError, T> • lift the error type from E to Nel<E> & accumulate errors • Combine all values when all fields are in Valid state • Keep invalid when at least one field is in Invalid state
  • 24. In Action 🛠 (Kotlin)
  • 25. Take away 🥡🍜 Validation is an easy problem which can be solved with just 2 things : ✓Appropriate data structures (some may say ADT) to model errors & to model validation results ✓An abstraction to express independent computations (Applicative)
  • 26. 💡There gotta be a better way ! 🤔 (Again & again !!!) This is nice and all but…
  • 27. Can we go further ? 🚀 • 💡We could try to make impossible states unrepresentable • There is this thing called Refined • Let’s see some Scala… 
 (sorry I’m not fluent in Haskell 🙊)
  • 29. Not there yet ! 💫 • Clearly I’m not an expert (but if you are, let’s talk 🤩) • Even for a simple case like Validation research is important • Mathematics are the (best) base tool at hand
  • 30. Q&A time Thanks for listening @enhan on Github & @nhanmanu on Twitter
  • 31. References & credits • Code: • https://github.com/enhan/oop-to-fp-validation • https://github.com/enhan/refined-validation • Articles: • https://typelevel.org/cats/datatypes/validated.html • https://arrow-kt.io/docs/arrow/data/validated/ • https://www.enhan.eu/how-to-in-fp/
  • 32. References & credits • Books: • Functional Programming in Scala (Paul Chiusano and Runar Bjarnason) • Category Theory for Programmers (Bartosz Milewski)
  • 33. References & credits • Libs: • Spring: https://spring.io/ • Arrow: https://arrow-kt.io/ • Cats: https://typelevel.org/cats/ • Refined: https://github.com/fthomas/refined
  • 34. References & credits • Pictures (all from unsplash, in order) : • SpaceX • Anthony Cantin • Mirko Blicke • Simon Caspersen • Alexey Sukhariev • Designecologist