Railway Oriented Programming with Groovy
OR
Introducing Either Monad in Groovy
By - Prakash Balodi
I Am
Software Engineer @ Quintype Inc.
Prakash Balodi
Agenda
- State of the art
- What is Railway Oriented Approach
- the ‘M’ word
State of the Art!
-
Error Handling is always an implicit requirement.
-
Can be the difference between Good code and bad code.
Error Handling traditionally
-
Lot of conditionals (switch)
-
Especially ugly if method calls are large chains
var i=method1()
if(!i){
return;
}
var j=function2();
if(!j){
return;
}
.
.
.
Error Handling traditionally!
-
Or We can use exceptions!
-
But Exceptions are -
-
Not Local Solutions
-
Can leak abstractions!
-
Functions are no longer pure!
-
It's a know phenomenon that error propagation spreads like a disease throughout the code!
- The Internet
Can we do better?
The Imperative Model for Error Handling
The Railway Model for Error Handling
Note that we always move forward!
With Railway oriented Model, we write our functions as -
so every function can either return a success value or a failure value.
=
Now what we need is some way to connect these functions
And then we can join these functions -
We can add as many joins as we want!
But How do we Model Both Success and Failure coming out of a function?
- Functions return one value
- Need to Return both Success and Failure
- In comes Either Monad!
What's Either?
- Data structure that can hold one of two values
- Also known as Disjoint Union
- Has two parts (Left and Right)
- Only one of them can have value at a given time.
What's Either?
- So if we can return value of type either, we can represent both success and failure from a function!
And How do we connect multiple functions?
Either has a bind function!
- Either by convention should have a bind function that allows you to glue functions together.
- Helps in composing functions to create function chains.
Thanks!
-
Railway Oriented Programming - https://www.youtube.com/watch?v=UvD1VjRvGIk
- FP and Battle for survival - https://www.youtube.com/watch?v=_6cDgwIHtQw
- Functional Groovy - http://mariogarcia.github.io/functional-groovy/
- Code samples - https://github.com/prakash23/rop-groovy
Railway Oriented Programming with Groovy
By Prakash Balodi
Railway Oriented Programming with Groovy
Presentation for TTN monday session
- 1,262