SlideShare a Scribd company logo
From OOP to FP
✅ The Validation case
Emmanuel Nhan - JUG Toulouse 11 juin 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 (found that in the docs): 

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 ThresholdBNotGreater(!/*…!*/):
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 look 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> (leftMap)
Validating many
• Validating field A is independent of validating field B

• We need a function, with the shape :

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

(ValidatedNel<E,A>,ValidatedNel<E,B>,

(A,B) !-> C) !-> ValidatedNel<E, C>
• 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 a (simple) problem which can be solved with
just 2 things :

✓Appropriate data structures (some may say ADT) 

to model errors & 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
possible
values for A
acceptable
values for A
acceptable
values for A
Validation :
Uses a predicate to determine
the acceptable subset of A
Is it possible to encode this in code ?
Type system ✨
• Predicate encoding in the type system

• Compiler automatic derivation

• There is this thing called Refined

• Let’s see some (hardcore) 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/

• http://lara.epfl.ch/~kuncak/papers/
SchmidKuncak16CheckingPredicate.pdf
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

PDF
From OOP to FP: The validation case
PPTX
Clean Code
PDF
Swift testing ftw
PDF
Living With Legacy Code
PPTX
C sharp fundamentals Part I
PDF
Working Effectively with Legacy Code: Lessons in Practice
PPTX
JAVASCRIPT - LinkedIn
PPTX
Building unit tests correctly with visual studio 2013
From OOP to FP: The validation case
Clean Code
Swift testing ftw
Living With Legacy Code
C sharp fundamentals Part I
Working Effectively with Legacy Code: Lessons in Practice
JAVASCRIPT - LinkedIn
Building unit tests correctly with visual studio 2013

What's hot (20)

PDF
Writing tests
PDF
Introduction to kotlin for Java Developer
ODP
Can't Dance The Lambda
PDF
How do i - create a native interface
PPT
JavaScript Introductin to Functions
PPTX
Battle of The Mocking Frameworks
PDF
Xtend - better java with -less- noise
PPTX
Test in action – week 1
PPT
EasyMock for Java
PDF
Working With Legacy Code
PDF
PDF
Typed Drupal - A great combination of Drupal 8 and PHP7
PPTX
Java script basic
PDF
Testing Legacy Rails Apps
PDF
Unit testing legacy code
PPTX
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
PDF
Testdriven Development using JUnit and EasyMock
PPTX
Working Effectively with Legacy Code
PDF
Functional programming with Xtend
Writing tests
Introduction to kotlin for Java Developer
Can't Dance The Lambda
How do i - create a native interface
JavaScript Introductin to Functions
Battle of The Mocking Frameworks
Xtend - better java with -less- noise
Test in action – week 1
EasyMock for Java
Working With Legacy Code
Typed Drupal - A great combination of Drupal 8 and PHP7
Java script basic
Testing Legacy Rails Apps
Unit testing legacy code
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Testdriven Development using JUnit and EasyMock
Working Effectively with Legacy Code
Functional programming with Xtend

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

PPTX
Building unit tests correctly
PPTX
Unit tests & TDD
PPT
CPP10 - Debugging
PPTX
DefensiveProgramming (1).pptx
PDF
Getting Started With Testing
PPT
Agile latvia evening_unit_testing_in_practice
PDF
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
PDF
iOS Test-Driven Development
PDF
DSR Testing (Part 1)
KEY
Php Code Audits (PHP UK 2010)
PPTX
Unit testing
PPTX
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
PDF
2600 Thailand #50 From 0day to CVE
PDF
Exception handling in Ruby
PPTX
Test automation expert days
PPTX
Angular Unit Test
PDF
Jest: Frontend Testing richtig gemacht @WebworkerNRW
PPTX
Working with Legacy Code
PDF
Writing clean code
PPTX
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games
Building unit tests correctly
Unit tests & TDD
CPP10 - Debugging
DefensiveProgramming (1).pptx
Getting Started With Testing
Agile latvia evening_unit_testing_in_practice
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
iOS Test-Driven Development
DSR Testing (Part 1)
Php Code Audits (PHP UK 2010)
Unit testing
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
2600 Thailand #50 From 0day to CVE
Exception handling in Ruby
Test automation expert days
Angular Unit Test
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Working with Legacy Code
Writing clean code
We Love Performance! How Tic Toc Games Uses ECS in Mobile Puzzle Games

Recently uploaded (20)

PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Welding lecture in detail for understanding
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
Geodesy 1.pptx...............................................
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPT
Mechanical Engineering MATERIALS Selection
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Welding lecture in detail for understanding
UNIT 4 Total Quality Management .pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
R24 SURVEYING LAB MANUAL for civil enggi
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
CH1 Production IntroductoryConcepts.pptx
OOP with Java - Java Introduction (Basics)
Automation-in-Manufacturing-Chapter-Introduction.pdf
Lecture Notes Electrical Wiring System Components
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Geodesy 1.pptx...............................................
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Embodied AI: Ushering in the Next Era of Intelligent Systems
Mechanical Engineering MATERIALS Selection

From OOP to FP : the validation case

  • 1. From OOP to FP ✅ The Validation case Emmanuel Nhan - JUG Toulouse 11 juin 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 (found that in the docs): 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 ThresholdBNotGreater(!/*…!*/): 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 look 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> (leftMap)
  • 21. Validating many • Validating field A is independent of validating field B • We need a function, with the shape : (F<A>,F<B>,(A,B) !-> C) !-> F<C> • Where F is a type like ValidatedNel with a fixed type:
 (ValidatedNel<E,A>,ValidatedNel<E,B>,
 (A,B) !-> C) !-> ValidatedNel<E, C> • 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 a (simple) problem which can be solved with just 2 things : ✓Appropriate data structures (some may say ADT) 
 to model errors & 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 possible values for A acceptable values for A acceptable values for A Validation : Uses a predicate to determine the acceptable subset of A Is it possible to encode this in code ?
  • 28. Type system ✨ • Predicate encoding in the type system • Compiler automatic derivation • There is this thing called Refined • Let’s see some (hardcore) Scala… 
 (sorry I’m not fluent in Haskell 🙊)
  • 30. 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
  • 31. Q&A time Thanks for listening @enhan on Github & @nhanmanu on Twitter
  • 32. 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/ • http://lara.epfl.ch/~kuncak/papers/ SchmidKuncak16CheckingPredicate.pdf
  • 33. References & credits • Books: • Functional Programming in Scala (Paul Chiusano and Runar Bjarnason) • Category Theory for Programmers (Bartosz Milewski)
  • 34. References & credits • Libs: • Spring: https://spring.io/ • Arrow: https://arrow-kt.io/ • Cats: https://typelevel.org/cats/ • Refined: https://github.com/fthomas/refined
  • 35. References & credits • Pictures (all from unsplash, in order) : • SpaceX • Anthony Cantin • Mirko Blicke • Simon Caspersen • Alexey Sukhariev • Designecologist