SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Try the Monad!
Streamlining error management in Grails 4
Who am I?
● Luis Muñiz, level 25 JVM Developer
● New Madrileño
● CTO at Sparkers
your entertainment data companion
all things entertainment.
Gaming. Books. Movies.
Streaming. Etc.
Sparkers
Disclaimer(s)
Overview What about Errors?
Why we don’t like how Spring does it?
How we solve it?
How does it affect Grails artifacts?
What about Errors? An error can happen anywhere
We want central error management
Near the point of entry, to provide alternative
response to happy scenario
But this is far away from the error, loss of context
Analyzing the cause is harder
Hard to recover out of context
How Spring does it -
try {
An error can happen anywhere
=> Throw from anywhere
=> Basically GOTO
We want central error management.
Near the point of entry, to provide alternative
response to happy scenario.
=> Exception handlers FTW
=> Error case statically coupled to Exception class
But this is far away from the error, loss of context.
Analyzing the cause is harder.
Hard to recover out of context.
=> You won’t have a clue anyway how to recover from
an exception handler
How Spring does it -
catch {
Complex, static Exception Hierarchies
Catch, log, and re-throw
● Hunt the logs for error causes
● Goodbye consistent error handling
Catch and swallow
● Who knows where this came from anyway?
● Let’s hope for the best
Throw in Transaction rollback for free
● Checked exceptions become a problem
How Spring does it -
catch {
finally { Unchecked Exceptions are not really your friend
Checked exceptions are most certainly not your friend
Most code, unless trivial, is not exception-safe
Expensive to throw
Memory leaks, unclosed files, sockets, partially
written files
Brittle Applications, without intelligent error recovery
Don’t take my word for it
Enough Complaining!
What we need Error Handling next to point of entry
Preserve context
Don’t break flow of control, don’t break function
composition
Allow local or global recovery mechanisms
Our Solution
Error Handling next to point
of entry
Embrace HTTP status codes, even if your
application does not do HTTP
● OK means OK, NOT_FOUND means Not Found,
even if you’re not a web server
● ErrorContext Runtime Exception and factory
methods.
ErrorContext factory methods
ErrorContext is a RuntimeException with:
● code (from HTTP status codes)
● extendedCode (for sub-categories)
● context (for ….. context)
Our Solution
flow of control
function composition
Renounce exceptions and embrace return types
● Never let a function throw an exception
● Enter Javaslang (cough) VAVR’s Try Monad
Our Solution
flow of control
function composition
Try<T>
Parameterized type that represents either:
● Try.Success<T>: successful invocation,
embedding the return value of type T
● Try.Failure<T>: unsuccessful invocation,
embedding a Throwable
Don’t break Flow of Control
Try.of {
}
instead of
try {
} catch() {
}
Don’t break Function Composition
Conditional function
composition with monadic
functions:
● map()
● flatMap()
Functions are only composed if
Try object is a Try.Success,
otherwise the Try.Failure is
returned directly.
or...
Sidenote ;-)
Function Composition is at the heart of intuitively understanding
what Monads are good for (1-slide challenge)
In classical languages:
● Function Composition is “hardcoded” into the semantics and
syntax of the language
● f(g(x)) means: “first call g(x) and feed the result into f()”
⇒ g(x).map(f), in monads, means “compose”
● In Monad Try, composition means: only compose with f if g(x) is
not a Try.Failure
● In Monad Future, composition means: compose with f when
value in g(x) is available
● In Monad List, composition means: apply f to each element of
g(x)
Functional languages with native monads, have nicer syntax for this:
Success and Failure
Failure to Success: Recovery
recover -> map
recoverWith -> flatMap
Success to Failure
Integrated in Grails 4
Our customizations: Layers (Author Resource)
Our customizations: REST Controller
No apparent error handling.
This is done in the ControllerResponses Trait
Our customizations: ControllerResponses (success)
Our customizations: ControllerResponses (failure)
/views/errorContext/_errorContext.gson
Our customizations: Command Object
Our customizations: Façade Service, Transaction Demarcation
Our customizations: Data Service
Key Takeaways
Honest functions The functions announce their return type and promise
not to kick you by throwing exceptions.
In Control Your application can, if needed attempt recovery
close to the source of the error, and still keep the
feature to let errors trickle down into the controller
for handling.
Very simple and
generic Controllers
Thanks to Traits specialized in error handling and
Command objects, the controller methods usually are
reduced to one-liners.
Explicit Transaction
Management
You decide where transactions are rolled back, and
you don’t get rollbacks due to unexpected runtime
exceptions deep in your service layer.
Command Objects
Orchestrate Logic
Your Command objects are no longer dumb Value
Objects but fullfill the function to orchestrate your
use case.
We’re hiring!
https:/
/apply.workable.com/sparkers
Embrace the Monad

Weitere ähnliche Inhalte

Was ist angesagt?

Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Vijay Kumbhar
 
Essential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricksEssential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricksKaloyan Raev
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018Paulo Clavijo
 
Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...Alberto Lluch Lafuente
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 

Was ist angesagt? (7)

Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy
 
Essential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricksEssential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricks
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018
 
Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...
 
Switch statement
Switch statementSwitch statement
Switch statement
 
XP in the full stack
XP in the full stackXP in the full stack
XP in the full stack
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 

Ähnlich wie Try the monad!

Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Francisco Amores
 
Reconciling Functional Programming and Exceptions
Reconciling Functional Programming and ExceptionsReconciling Functional Programming and Exceptions
Reconciling Functional Programming and ExceptionsSeamus Mc Gonigle
 
Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1Muhamad Hesham
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsDirecti Group
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsJaneve George
 
Introduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerIntroduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerNaoto Ono
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoringGrokking VN
 
MapReduce: teoria e prática
MapReduce: teoria e práticaMapReduce: teoria e prática
MapReduce: teoria e práticaPET Computação
 
Best Practices in PHP Application Deployment
Best Practices in PHP Application DeploymentBest Practices in PHP Application Deployment
Best Practices in PHP Application DeploymentShahar Evron
 
Code quality
Code qualityCode quality
Code quality44ue
 
Cucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxCucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxKalhan Liyanage
 
Functional Programming - Worth the Effort
Functional Programming - Worth the EffortFunctional Programming - Worth the Effort
Functional Programming - Worth the EffortBoldRadius Solutions
 
Tips about hibernate with spring data jpa
Tips about hibernate with spring data jpaTips about hibernate with spring data jpa
Tips about hibernate with spring data jpaThiago Dos Santos Hora
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowKathy Brown
 
Systematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zioSystematic error management - we ported rudder to zio
Systematic error management - we ported rudder to ziofanf42
 
Structured Software Design
Structured Software DesignStructured Software Design
Structured Software DesignGiorgio Zoppi
 

Ähnlich wie Try the monad! (20)

Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)
 
Reconciling Functional Programming and Exceptions
Reconciling Functional Programming and ExceptionsReconciling Functional Programming and Exceptions
Reconciling Functional Programming and Exceptions
 
Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Introduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerIntroduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debugger
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoring
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
MapReduce: teoria e prática
MapReduce: teoria e práticaMapReduce: teoria e prática
MapReduce: teoria e prática
 
Best Practices in PHP Application Deployment
Best Practices in PHP Application DeploymentBest Practices in PHP Application Deployment
Best Practices in PHP Application Deployment
 
Code quality
Code qualityCode quality
Code quality
 
Clean code
Clean codeClean code
Clean code
 
Cucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxCucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptx
 
Functional Programming - Worth the Effort
Functional Programming - Worth the EffortFunctional Programming - Worth the Effort
Functional Programming - Worth the Effort
 
Tips about hibernate with spring data jpa
Tips about hibernate with spring data jpaTips about hibernate with spring data jpa
Tips about hibernate with spring data jpa
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To Know
 
Systematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zioSystematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zio
 
Structured Software Design
Structured Software DesignStructured Software Design
Structured Software Design
 

Kürzlich hochgeladen

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Kürzlich hochgeladen (20)

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Try the monad!

  • 1. Try the Monad! Streamlining error management in Grails 4
  • 2. Who am I? ● Luis Muñiz, level 25 JVM Developer ● New Madrileño ● CTO at Sparkers
  • 3. your entertainment data companion all things entertainment. Gaming. Books. Movies. Streaming. Etc. Sparkers
  • 5. Overview What about Errors? Why we don’t like how Spring does it? How we solve it? How does it affect Grails artifacts?
  • 6. What about Errors? An error can happen anywhere We want central error management Near the point of entry, to provide alternative response to happy scenario But this is far away from the error, loss of context Analyzing the cause is harder Hard to recover out of context
  • 7. How Spring does it - try { An error can happen anywhere => Throw from anywhere => Basically GOTO We want central error management. Near the point of entry, to provide alternative response to happy scenario. => Exception handlers FTW => Error case statically coupled to Exception class But this is far away from the error, loss of context. Analyzing the cause is harder. Hard to recover out of context. => You won’t have a clue anyway how to recover from an exception handler
  • 8. How Spring does it - catch { Complex, static Exception Hierarchies Catch, log, and re-throw ● Hunt the logs for error causes ● Goodbye consistent error handling Catch and swallow ● Who knows where this came from anyway? ● Let’s hope for the best Throw in Transaction rollback for free ● Checked exceptions become a problem
  • 9. How Spring does it - catch {
  • 10. finally { Unchecked Exceptions are not really your friend Checked exceptions are most certainly not your friend Most code, unless trivial, is not exception-safe Expensive to throw Memory leaks, unclosed files, sockets, partially written files Brittle Applications, without intelligent error recovery Don’t take my word for it
  • 12. What we need Error Handling next to point of entry Preserve context Don’t break flow of control, don’t break function composition Allow local or global recovery mechanisms
  • 13. Our Solution Error Handling next to point of entry Embrace HTTP status codes, even if your application does not do HTTP ● OK means OK, NOT_FOUND means Not Found, even if you’re not a web server ● ErrorContext Runtime Exception and factory methods.
  • 14. ErrorContext factory methods ErrorContext is a RuntimeException with: ● code (from HTTP status codes) ● extendedCode (for sub-categories) ● context (for ….. context)
  • 15. Our Solution flow of control function composition Renounce exceptions and embrace return types ● Never let a function throw an exception ● Enter Javaslang (cough) VAVR’s Try Monad
  • 16. Our Solution flow of control function composition Try<T> Parameterized type that represents either: ● Try.Success<T>: successful invocation, embedding the return value of type T ● Try.Failure<T>: unsuccessful invocation, embedding a Throwable
  • 17. Don’t break Flow of Control Try.of { } instead of try { } catch() { }
  • 18. Don’t break Function Composition Conditional function composition with monadic functions: ● map() ● flatMap() Functions are only composed if Try object is a Try.Success, otherwise the Try.Failure is returned directly. or...
  • 19. Sidenote ;-) Function Composition is at the heart of intuitively understanding what Monads are good for (1-slide challenge) In classical languages: ● Function Composition is “hardcoded” into the semantics and syntax of the language ● f(g(x)) means: “first call g(x) and feed the result into f()” ⇒ g(x).map(f), in monads, means “compose” ● In Monad Try, composition means: only compose with f if g(x) is not a Try.Failure ● In Monad Future, composition means: compose with f when value in g(x) is available ● In Monad List, composition means: apply f to each element of g(x) Functional languages with native monads, have nicer syntax for this:
  • 21. Failure to Success: Recovery recover -> map recoverWith -> flatMap
  • 24. Our customizations: Layers (Author Resource)
  • 25. Our customizations: REST Controller No apparent error handling. This is done in the ControllerResponses Trait
  • 27. Our customizations: ControllerResponses (failure) /views/errorContext/_errorContext.gson
  • 29. Our customizations: Façade Service, Transaction Demarcation
  • 32. Honest functions The functions announce their return type and promise not to kick you by throwing exceptions. In Control Your application can, if needed attempt recovery close to the source of the error, and still keep the feature to let errors trickle down into the controller for handling. Very simple and generic Controllers Thanks to Traits specialized in error handling and Command objects, the controller methods usually are reduced to one-liners. Explicit Transaction Management You decide where transactions are rolled back, and you don’t get rollbacks due to unexpected runtime exceptions deep in your service layer. Command Objects Orchestrate Logic Your Command objects are no longer dumb Value Objects but fullfill the function to orchestrate your use case.