monads in practice
DESCRIPTION
Lecture demistifying monads. After talking a bit about Monoids and Functor I explain a functional design technics which is Monad through the refactoring of a JDBC code. Talk given at The Developper Conference in Porto Alegre in 2014 (http://www.thedevelopersconference.com.br), Code source of the presentation is in my github: https://github.com/toff63/monads-in-practice-tdcTRANSCRIPT
Monads in Practice
Christophe Marchal | Software Architect
A couple of links
http://francesbagual.net
@toff63
http://github.com/toff63
Disclaimer
Manage complexity with Monad
Study Monads online is hard
Academic talks
Func
tor
Monoids
Monads
Category theory
Category Theory
Function
Monoids
Associative
( 1 + 2 ) + 3 = 1 + ( 2 + 3 )
InitiAl Value
Result stay in the same
category
Monoid Example
Monoid
FunctorThings that can be map over
map
capacityBEHaviour
Functor: Example
Functor: Example
Monads
Problem it solves
Scenario
F 1 F 2
sweet
Monads Rules: function to create it
Broken Composition
F 1
F 2
sweet
F 1
map ( f 2 )
sweet
Monads Rules: You need a Functor
Scenario
F 1 F 3
sweet
F 1
sweet
Problem: Nested Monad
map ( f 3 )
sweet
F 1
sweet
Flatmap ( f 3 )
Monads Rules: You need a Flatmap
Business rule
age > 18
AuthorizedNot
Authorized
TRUE False
Business rule implementation
What we want
Monad (?) Code
Trade-off
More code than before
Better API
Easy to reuse
Potential complexity Managed
Traditional Code
Side Effect
Our method can return either a sequence
either null
Exist?
null ?
Riendutout quelquechose
TRUE False
Encapsulating if null with Option
Creating our OptionBagual
Code with Options
Business code
Side Effect
Our method can return either an option
[sequence] either throw an exception
Try!
Try to
execute
Gremio Inter
Success Failure
Encapsulating try/catch with Try
Encapsulating try/catch with Try
Code with Try
Business code
Connection Handling
No silver bullet
Loan Pattern
Final Code
Conclusion
● NO IFs
● Border cases handled on demand
● More declarative types
● Highlight business code
● Easy to create
● More reusable code
Thank You!
Christophe Marchal | Software Architect