SlideShare a Scribd company logo
Functional	Effects
Part	1
learn	about	functional	effects through	the	work	of
slides	by @philip_schwarz
Debasish	Ghosh	
@debasishg
https://www.slideshare.net/pjschwarz
Functional thinking and implementing with pure functions is a great engineering discipline for your domain model. But you also
need language support that helps build models that are responsive to failures, scales well with increasing load, and delivers a
nice experience to users. Chapter 1 referred to this characteristic as being reactive, and identified the following two aspects that
you need to address in order to make your model reactive:
• Manage failures, also known as design for failure
• Minimize latency by delegating long-running processes to background threads without blocking the main thread of
execution
In this section, you’ll see how Scala offers abstractions that help you address both of these issues. You can manage exceptions
and latency as effects that compose along with the other pure abstractions of your domain model. An effect adds capabilities
to your computation so that you don’t need to use side effects to model them. The sidebar “What is an effectful computation?”
details what I mean.
Managing exceptions is a key component of reactive models—you need to ensure that a failing component doesn’t bring down
the entire application. And managing latency is another key aspect that you need to take care of—unbounded latency through
blocking calls in your application is a severe antipattern of good user experience. Luckily, Scala covers both of them by
providing abstractions as part of the standard library.
What is an effectful computation?
In functional programming, an effect adds some capabilities to a computation. And because we’re dealing with a statically typed
language, these capabilities come in the form of more power from the type system. An effect is modeled usually in the form of a
type constructor that constructs types with these additional capabilities.
Say you have any type A and you’d like to add the capability of aggregation, so that you can treat a collection of A as a separate
type. You do this by constructing a type List[A] (for which the corresponding type constructor is List), which adds the effect of
aggregation on A. Similarly, you can have Option[A] that adds the capability of optionality for the type A.
In the next section, you’ll learn how to use type constructors such as Try and Future to model the effects of exceptions and
latency, respectively. In chapter 4 we’ll discuss more advanced effect handling using applicatives and monads.
@debasishg
Debasish	Ghosh
2.6.1 Managing effects
When we’re talking about exceptions, latency, and so forth in the context of making your model reactive, you must be
wondering how to adapt these concepts into the realm of functional programming. Chapter 1 called these side effects and
warned you about the cast of gloom that they bring to your pure domain logic. Now that we’re talking about managing them to
make our models reactive, how should you treat them as part of your model so that they can be composed in a referentially
transparent way along with the other domain elements?
In Scala, you treat them as effects, in the sense that you abstract them within containers that expose functional interfaces
to the world. The most common example of treating exceptions as effects in Scala is the Try abstraction, which you saw
earlier. Try provides a sum type, with one of the variants (Failure) abstracting the exception that your computation can
raise. Try wraps the effect of exceptions within itself and provides a purely functional interface to the user. In the more
general sense of the term, Try is a monad. There are some other examples of effect handling as well. Latency is another
example, which you can treat as an effect—instead of exposing the model to the vagaries of unbounded latency, you use
constructs such as Future that act as abstractions to manage latency. You’ll see some examples shortly.
The concept of a monad comes from category theory. This book doesn’t go into the theoretical underpinnings of a monad as a
category. It focuses more on monads as abstract computations that help you mimic the effects of typically impure actions
such as exceptions, I/O, continuations, and so forth while providing a functional interface to your users. And we’ll limit
ourselves to the monadic implementations that some of the Scala abstractions such as Try and Future offer. The only
takeaway on what a monad does in the context of functional and reactive domain modeling is that it abstracts effects and lets
you play with a pure functional interface that composes nicely with the other components.
@debasishg
Debasish	Ghosh
effect
failure
latency
Try
Future
monad
pure	functional	interface
abstract	computation
aggregation
optionality
type	constructor
capability
List
Option
exceptions
effectful computationcomputation
adds
to resuting	in
abstracts	– helps	you	mimic	– allows	the	handling	of
provides
allows	
modeling	
of abstraction
to	manage
pure abstractions
composes	
along	with	
other
side	effect
so	there	is	no	
need	to	use	a
Key	terms	and	concepts	
seen	so	far
@philip_schwarz
def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal): Try[BigDecimal] = ???
def getCurrencyBalance[A <: SavingsAccount](account: A): Try[BigDecimal] = ???
def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Try[BigDecimal] = ???
val account: SavingsAccount = ???
val result: Try[BigDecimal] = for {
balance ⃪ getCurrencyBalance(account)
interest ⃪ calculateInterest(account, balance)
value ⃪ calculateNetAssetValue(account, balance, interest)
} yield value
result match {
case Success(v) => ??? // .. success
case Failure(ex) => ??? // .. failure
}
Listing 2.13 shows three functions, each of which can fail in some circumstances. We make that fact loud and clear—instead of BigDecimal, these
functions return Try[BigDecimal].
You’ve seen Try before and know how it abstracts exceptions within your Scala code. Here, by returning a Try, the function makes it explicit that it can
fail. If all is good and happy, you get the result in the Success branch of the Try, and if there’s an exception, then you get it from the Failure variant.
The most important point to note is that the exception never escapes from the Try as an unwanted side effect to pollute your compositional code. Thus
you’ve achieved the first promise of the two-pronged strategy of failure management in Scala: being explicit about the fact that this function can fail.
But what about the promise of compositionality? Yes, Try also gives you
that by being a monad and offering a lot of higher-order functions. Here’s the
flatMap method of Try that makes it a monad and helps you compose
with other functions that may fail:
def flatMap[U](f: T => Try[U]): Try[U]
You saw earlier how flatMap binds together computations and helps you
write nice, sequential for-comprehensions without forgoing the goodness of
expression-oriented evaluation. You can get the same goodness with Try
and compose code that may fail:
This code handles all exceptions, composes nicely, and expresses the intent of the code in a clear and succinct manner. This is what you get when you
have powerful language abstractions to back your domain model. Try is the abstraction that handles the exceptions, and flatMap is the secret sauce
that lets you program through the happy path. So you can now have domain model elements that can throw exceptions—just use the Try abstraction for
managing the effects and you can make your code resilient to failures.
@debasishg
Debasish	Ghosh
Functional	and	Reactive	
Domain	Modeling
Managing Failures
Managing Latency
def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal):Future[BigDecimal] = ???
def getCurrencyBalance[A <: SavingsAccount](account: A): Future[BigDecimal] = ???
def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Future[BigDecimal] = ???
val account: SavingsAccount = ???
implicit val ec: ExecutionContext = ???
val result: Future[BigDecimal] = for {
balance ⃪ getCurrencyBalance(account)
interest ⃪ calculateInterest(account, balance)
value ⃪ calculateNetAssetValue(account, balance, interest)
} yield value
result onComplete {
case Success(v) => ??? //.. success
case Failure(ex) => ??? //.. failure
}
Just as Try manages exceptions using effects, another abstraction in the Scala library called Future helps you manage latency as an effect. What does that
mean? Reactive programming suggests that our model needs to be resilient to variations in latency, which may occur because of increased load on the system
or network delays or many other factors beyond the control of the implementer. To provide an acceptable user experience with respect to response time, our
model needs to guarantee some bounds on the latency.
The idea is simple: Wrap your long-running computations in a Future. The computation will be delegated to a background thread, without blocking
the main thread of execution. As a result, the user experience won’t suffer, and you can make the result of the computation available to the user whenever you
have it. Note that this result can also be a failure, in case the computation failed—so Future handles both latency and exceptions as effects.
@debasishg
Debasish	Ghosh
Functional	and	Reactive	
Domain	Modeling
Future is also a monad, just like Try, and has the flatMap method
that helps you bind your domain logic to the happy path of
computation… imagine that the functions you wrote in listing 2.13
involve network calls, and thus there’s always potential for long latency
associated with each of them. As I suggested earlier, let’s make this explicit
to the user of our API and make each of the functions return Future:
By using flatMap, you can now compose the functions sequentially to yield another Future. The net effect is that the entire computation is delegated to
a background thread, and the main thread of execution remains free. Better user experience is guaranteed, and you’ve implemented what the reactive
principles talk about—systems being resilient to variations in network latency. The following listing demonstrates the sequential composition of futures in
Scala.
Here, result is also a Future, and you can plug in callbacks for the success and failure paths of the completed Future. If the Future completes
successfully, you have the net asset value that you can pass on to the client. If it fails, you can get that exception as well and implement custom
processing of the exception.
def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal): Try[BigDecimal] = ???
def getCurrencyBalance[A <: SavingsAccount](account: A): Try[BigDecimal] = ???
def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Try[BigDecimal] = ???
val account: SavingsAccount = ???
val result: Try[BigDecimal] = for {
balance <- getCurrencyBalance(account)
interest <- calculateInterest(account, balance)
value <- calculateNetAssetValue(account, balance, interest)
} yield value
result match {
case Success(v) => ??? // .. success
case Failure(ex) => ??? // .. failure
}
def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal): Future[BigDecimal] = ???
def getCurrencyBalance[A <: SavingsAccount](account: A): Future[BigDecimal] = ???
def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Future[BigDecimal] = ???
val account: SavingsAccount = ???
implicit val ec: ExecutionContext = ???
val result: Future[BigDecimal] = for {
balance <- getCurrencyBalance(account)
interest <- calculateInterest(account, balance)
value <- calculateNetAssetValue(account, balance, interest)
} yield value
result onComplete {
case Success(v) => ??? //.. success
case Failure(ex) => ??? //.. failure
}
Managing Failures
Managing Latency
That was great. Functional and Reactive Domain Modeling is a very nice book.
I’ll leave you with a question: are Try and Future lawful monads? See the following for
an introduction to monad laws and how to check if they are being obeyed:
https://www.slideshare.net/pjschwarz/monad-laws-must-be-checked-107011209
@philip_schwarz
Monad Laws Must be Checked

More Related Content

What's hot

Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
Philip Schwarz
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
Philip Schwarz
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
Philip Schwarz
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Philip Schwarz
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Philip Schwarz
 
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1
Philip Schwarz
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Philip Schwarz
 
Kleisli Composition
Kleisli CompositionKleisli Composition
Kleisli Composition
Philip Schwarz
 
Function Composition - forward composition versus backward composition
Function Composition - forward composition versus backward compositionFunction Composition - forward composition versus backward composition
Function Composition - forward composition versus backward composition
Philip Schwarz
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Natural Transformations
Natural TransformationsNatural Transformations
Natural Transformations
Philip Schwarz
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
Sangeetha Sg
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
Mohammed Sikander
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
Md.Mojibul Hoque
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
Scott Wlaschin
 

What's hot (20)

Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
 
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
 
Kleisli Composition
Kleisli CompositionKleisli Composition
Kleisli Composition
 
Function Composition - forward composition versus backward composition
Function Composition - forward composition versus backward compositionFunction Composition - forward composition versus backward composition
Function Composition - forward composition versus backward composition
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Natural Transformations
Natural TransformationsNatural Transformations
Natural Transformations
 
Scala functions
Scala functionsScala functions
Scala functions
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 

Similar to Functional Effects - Part 1

Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
Philip Schwarz
 
Sda 9
Sda   9Sda   9
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
Instant DBMS Homework Help
Instant DBMS Homework HelpInstant DBMS Homework Help
Instant DBMS Homework Help
Database Homework Help
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Thang Mai
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
Sameh Deabes
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
Book management system
Book management systemBook management system
Book management system
SHARDA SHARAN
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
guest38bf
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
ssuser84e52e
 
Vendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptxVendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptx
Guillaume Saint Etienne
 
Sdlc
SdlcSdlc
Sdlc
SdlcSdlc
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
Katy Slemon
 
Interaction overview and Profile UML Diagrams
Interaction overview and Profile UML DiagramsInteraction overview and Profile UML Diagrams
Interaction overview and Profile UML Diagrams
Husnain Safdar
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: Abstraction
JI Ruan
 
Matopt
MatoptMatopt
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
LK394
 
Bt0066 database management system2
Bt0066 database management system2Bt0066 database management system2
Bt0066 database management system2
Techglyphs
 
Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)
SiliconExpert Technologies
 

Similar to Functional Effects - Part 1 (20)

Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
 
Sda 9
Sda   9Sda   9
Sda 9
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
Instant DBMS Homework Help
Instant DBMS Homework HelpInstant DBMS Homework Help
Instant DBMS Homework Help
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
Book management system
Book management systemBook management system
Book management system
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
 
OOFeatures_revised-2.pptx
OOFeatures_revised-2.pptxOOFeatures_revised-2.pptx
OOFeatures_revised-2.pptx
 
Vendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptxVendredi Tech_ la programmation fonctionnelle.pptx
Vendredi Tech_ la programmation fonctionnelle.pptx
 
Sdlc
SdlcSdlc
Sdlc
 
Sdlc
SdlcSdlc
Sdlc
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Interaction overview and Profile UML Diagrams
Interaction overview and Profile UML DiagramsInteraction overview and Profile UML Diagrams
Interaction overview and Profile UML Diagrams
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: Abstraction
 
Matopt
MatoptMatopt
Matopt
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
 
Bt0066 database management system2
Bt0066 database management system2Bt0066 database management system2
Bt0066 database management system2
 
Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)Introduction To Programming (2009 2010)
Introduction To Programming (2009 2010)
 

More from Philip Schwarz

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Philip Schwarz
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
Philip Schwarz
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a series
Philip Schwarz
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a series
Philip Schwarz
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a series
Philip Schwarz
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
Philip Schwarz
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with Views
Philip Schwarz
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
Philip Schwarz
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in Scala
Philip Schwarz
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in Scala
Philip Schwarz
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
Philip Schwarz
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Philip Schwarz
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
Philip Schwarz
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Philip Schwarz
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Philip Schwarz
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
Philip Schwarz
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Philip Schwarz
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Philip Schwarz
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axioms
Philip Schwarz
 

More from Philip Schwarz (20)

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a series
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a series
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a series
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with Views
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in Scala
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in Scala
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axioms
 

Recently uploaded

APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 

Recently uploaded (20)

APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 

Functional Effects - Part 1

  • 2. Functional thinking and implementing with pure functions is a great engineering discipline for your domain model. But you also need language support that helps build models that are responsive to failures, scales well with increasing load, and delivers a nice experience to users. Chapter 1 referred to this characteristic as being reactive, and identified the following two aspects that you need to address in order to make your model reactive: • Manage failures, also known as design for failure • Minimize latency by delegating long-running processes to background threads without blocking the main thread of execution In this section, you’ll see how Scala offers abstractions that help you address both of these issues. You can manage exceptions and latency as effects that compose along with the other pure abstractions of your domain model. An effect adds capabilities to your computation so that you don’t need to use side effects to model them. The sidebar “What is an effectful computation?” details what I mean. Managing exceptions is a key component of reactive models—you need to ensure that a failing component doesn’t bring down the entire application. And managing latency is another key aspect that you need to take care of—unbounded latency through blocking calls in your application is a severe antipattern of good user experience. Luckily, Scala covers both of them by providing abstractions as part of the standard library. What is an effectful computation? In functional programming, an effect adds some capabilities to a computation. And because we’re dealing with a statically typed language, these capabilities come in the form of more power from the type system. An effect is modeled usually in the form of a type constructor that constructs types with these additional capabilities. Say you have any type A and you’d like to add the capability of aggregation, so that you can treat a collection of A as a separate type. You do this by constructing a type List[A] (for which the corresponding type constructor is List), which adds the effect of aggregation on A. Similarly, you can have Option[A] that adds the capability of optionality for the type A. In the next section, you’ll learn how to use type constructors such as Try and Future to model the effects of exceptions and latency, respectively. In chapter 4 we’ll discuss more advanced effect handling using applicatives and monads. @debasishg Debasish Ghosh
  • 3. 2.6.1 Managing effects When we’re talking about exceptions, latency, and so forth in the context of making your model reactive, you must be wondering how to adapt these concepts into the realm of functional programming. Chapter 1 called these side effects and warned you about the cast of gloom that they bring to your pure domain logic. Now that we’re talking about managing them to make our models reactive, how should you treat them as part of your model so that they can be composed in a referentially transparent way along with the other domain elements? In Scala, you treat them as effects, in the sense that you abstract them within containers that expose functional interfaces to the world. The most common example of treating exceptions as effects in Scala is the Try abstraction, which you saw earlier. Try provides a sum type, with one of the variants (Failure) abstracting the exception that your computation can raise. Try wraps the effect of exceptions within itself and provides a purely functional interface to the user. In the more general sense of the term, Try is a monad. There are some other examples of effect handling as well. Latency is another example, which you can treat as an effect—instead of exposing the model to the vagaries of unbounded latency, you use constructs such as Future that act as abstractions to manage latency. You’ll see some examples shortly. The concept of a monad comes from category theory. This book doesn’t go into the theoretical underpinnings of a monad as a category. It focuses more on monads as abstract computations that help you mimic the effects of typically impure actions such as exceptions, I/O, continuations, and so forth while providing a functional interface to your users. And we’ll limit ourselves to the monadic implementations that some of the Scala abstractions such as Try and Future offer. The only takeaway on what a monad does in the context of functional and reactive domain modeling is that it abstracts effects and lets you play with a pure functional interface that composes nicely with the other components. @debasishg Debasish Ghosh
  • 4. effect failure latency Try Future monad pure functional interface abstract computation aggregation optionality type constructor capability List Option exceptions effectful computationcomputation adds to resuting in abstracts – helps you mimic – allows the handling of provides allows modeling of abstraction to manage pure abstractions composes along with other side effect so there is no need to use a Key terms and concepts seen so far @philip_schwarz
  • 5. def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal): Try[BigDecimal] = ??? def getCurrencyBalance[A <: SavingsAccount](account: A): Try[BigDecimal] = ??? def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Try[BigDecimal] = ??? val account: SavingsAccount = ??? val result: Try[BigDecimal] = for { balance ⃪ getCurrencyBalance(account) interest ⃪ calculateInterest(account, balance) value ⃪ calculateNetAssetValue(account, balance, interest) } yield value result match { case Success(v) => ??? // .. success case Failure(ex) => ??? // .. failure } Listing 2.13 shows three functions, each of which can fail in some circumstances. We make that fact loud and clear—instead of BigDecimal, these functions return Try[BigDecimal]. You’ve seen Try before and know how it abstracts exceptions within your Scala code. Here, by returning a Try, the function makes it explicit that it can fail. If all is good and happy, you get the result in the Success branch of the Try, and if there’s an exception, then you get it from the Failure variant. The most important point to note is that the exception never escapes from the Try as an unwanted side effect to pollute your compositional code. Thus you’ve achieved the first promise of the two-pronged strategy of failure management in Scala: being explicit about the fact that this function can fail. But what about the promise of compositionality? Yes, Try also gives you that by being a monad and offering a lot of higher-order functions. Here’s the flatMap method of Try that makes it a monad and helps you compose with other functions that may fail: def flatMap[U](f: T => Try[U]): Try[U] You saw earlier how flatMap binds together computations and helps you write nice, sequential for-comprehensions without forgoing the goodness of expression-oriented evaluation. You can get the same goodness with Try and compose code that may fail: This code handles all exceptions, composes nicely, and expresses the intent of the code in a clear and succinct manner. This is what you get when you have powerful language abstractions to back your domain model. Try is the abstraction that handles the exceptions, and flatMap is the secret sauce that lets you program through the happy path. So you can now have domain model elements that can throw exceptions—just use the Try abstraction for managing the effects and you can make your code resilient to failures. @debasishg Debasish Ghosh Functional and Reactive Domain Modeling Managing Failures
  • 6. Managing Latency def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal):Future[BigDecimal] = ??? def getCurrencyBalance[A <: SavingsAccount](account: A): Future[BigDecimal] = ??? def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Future[BigDecimal] = ??? val account: SavingsAccount = ??? implicit val ec: ExecutionContext = ??? val result: Future[BigDecimal] = for { balance ⃪ getCurrencyBalance(account) interest ⃪ calculateInterest(account, balance) value ⃪ calculateNetAssetValue(account, balance, interest) } yield value result onComplete { case Success(v) => ??? //.. success case Failure(ex) => ??? //.. failure } Just as Try manages exceptions using effects, another abstraction in the Scala library called Future helps you manage latency as an effect. What does that mean? Reactive programming suggests that our model needs to be resilient to variations in latency, which may occur because of increased load on the system or network delays or many other factors beyond the control of the implementer. To provide an acceptable user experience with respect to response time, our model needs to guarantee some bounds on the latency. The idea is simple: Wrap your long-running computations in a Future. The computation will be delegated to a background thread, without blocking the main thread of execution. As a result, the user experience won’t suffer, and you can make the result of the computation available to the user whenever you have it. Note that this result can also be a failure, in case the computation failed—so Future handles both latency and exceptions as effects. @debasishg Debasish Ghosh Functional and Reactive Domain Modeling Future is also a monad, just like Try, and has the flatMap method that helps you bind your domain logic to the happy path of computation… imagine that the functions you wrote in listing 2.13 involve network calls, and thus there’s always potential for long latency associated with each of them. As I suggested earlier, let’s make this explicit to the user of our API and make each of the functions return Future: By using flatMap, you can now compose the functions sequentially to yield another Future. The net effect is that the entire computation is delegated to a background thread, and the main thread of execution remains free. Better user experience is guaranteed, and you’ve implemented what the reactive principles talk about—systems being resilient to variations in network latency. The following listing demonstrates the sequential composition of futures in Scala. Here, result is also a Future, and you can plug in callbacks for the success and failure paths of the completed Future. If the Future completes successfully, you have the net asset value that you can pass on to the client. If it fails, you can get that exception as well and implement custom processing of the exception.
  • 7. def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal): Try[BigDecimal] = ??? def getCurrencyBalance[A <: SavingsAccount](account: A): Try[BigDecimal] = ??? def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Try[BigDecimal] = ??? val account: SavingsAccount = ??? val result: Try[BigDecimal] = for { balance <- getCurrencyBalance(account) interest <- calculateInterest(account, balance) value <- calculateNetAssetValue(account, balance, interest) } yield value result match { case Success(v) => ??? // .. success case Failure(ex) => ??? // .. failure } def calculateInterest[A <: SavingsAccount](account: A, balance: BigDecimal): Future[BigDecimal] = ??? def getCurrencyBalance[A <: SavingsAccount](account: A): Future[BigDecimal] = ??? def calculateNetAssetValue[A <: SavingsAccount](account: A, ccyBalance: BigDecimal, interest: BigDecimal): Future[BigDecimal] = ??? val account: SavingsAccount = ??? implicit val ec: ExecutionContext = ??? val result: Future[BigDecimal] = for { balance <- getCurrencyBalance(account) interest <- calculateInterest(account, balance) value <- calculateNetAssetValue(account, balance, interest) } yield value result onComplete { case Success(v) => ??? //.. success case Failure(ex) => ??? //.. failure } Managing Failures Managing Latency
  • 8. That was great. Functional and Reactive Domain Modeling is a very nice book. I’ll leave you with a question: are Try and Future lawful monads? See the following for an introduction to monad laws and how to check if they are being obeyed: https://www.slideshare.net/pjschwarz/monad-laws-must-be-checked-107011209 @philip_schwarz Monad Laws Must be Checked