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

PDF
Functional Effects - Part 2
Philip Schwarz
 
PDF
non-strict functions, bottom and scala by-name parameters
Philip Schwarz
 
PDF
Applicative Functor - Part 2
Philip Schwarz
 
PDF
Unison Language - Contact
Philip Schwarz
 
PDF
Monad Fact #6
Philip Schwarz
 
PDF
Utility Classes
Philip Schwarz
 
PPTX
Writer Monad for logging execution of functions
Philip Schwarz
 
PDF
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Philip Schwarz
 
Functional Effects - Part 2
Philip Schwarz
 
non-strict functions, bottom and scala by-name parameters
Philip Schwarz
 
Applicative Functor - Part 2
Philip Schwarz
 
Unison Language - Contact
Philip Schwarz
 
Monad Fact #6
Philip Schwarz
 
Utility Classes
Philip Schwarz
 
Writer Monad for logging execution of functions
Philip Schwarz
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Philip Schwarz
 

What's hot (20)

PDF
Definitions of Functional Programming
Philip Schwarz
 
PDF
‘go-to’ general-purpose sequential collections - from Java To Scala
Philip Schwarz
 
PDF
The Expression Problem - Part 2
Philip Schwarz
 
PDF
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Philip Schwarz
 
PDF
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Philip Schwarz
 
PDF
The Expression Problem - Part 1
Philip Schwarz
 
PDF
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Philip Schwarz
 
PDF
Kleisli Composition
Philip Schwarz
 
PDF
Function Composition - forward composition versus backward composition
Philip Schwarz
 
PDF
Implicit conversion and parameters
Knoldus Inc.
 
PDF
Natural Transformations
Philip Schwarz
 
PPT
Scala functions
Knoldus Inc.
 
PPTX
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Jaliya Udagedara
 
PPTX
Java chapter 3
Munsif Ullah
 
PPTX
Objects and classes in Visual Basic
Sangeetha Sg
 
PPSX
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
PPTX
Pointer basics
Mohammed Sikander
 
PPTX
Code smells and remedies
Md.Mojibul Hoque
 
PDF
Scala categorytheory
Knoldus Inc.
 
PDF
An introduction to property based testing
Scott Wlaschin
 
Definitions of Functional Programming
Philip Schwarz
 
‘go-to’ general-purpose sequential collections - from Java To Scala
Philip Schwarz
 
The Expression Problem - Part 2
Philip Schwarz
 
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...
Philip Schwarz
 
The Expression Problem - Part 1
Philip Schwarz
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Philip Schwarz
 
Kleisli Composition
Philip Schwarz
 
Function Composition - forward composition versus backward composition
Philip Schwarz
 
Implicit conversion and parameters
Knoldus Inc.
 
Natural Transformations
Philip Schwarz
 
Scala functions
Knoldus Inc.
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Jaliya Udagedara
 
Java chapter 3
Munsif Ullah
 
Objects and classes in Visual Basic
Sangeetha Sg
 
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
Pointer basics
Mohammed Sikander
 
Code smells and remedies
Md.Mojibul Hoque
 
Scala categorytheory
Knoldus Inc.
 
An introduction to property based testing
Scott Wlaschin
 
Ad

Similar to Functional Effects - Part 1 (20)

PDF
Tagless Final Encoding - Algebras and Interpreters and also Programs
Philip Schwarz
 
PPTX
Sda 9
AmberMughal5
 
PDF
379008-rc217-functionalprogramming
Luis Atencio
 
PPTX
Instant DBMS Homework Help
Database Homework Help
 
PDF
Introduction to functional programming
Thang Mai
 
PPTX
GoF Design patterns I: Introduction + Structural Patterns
Sameh Deabes
 
PPTX
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
PDF
Book management system
SHARDA SHARAN
 
PPT
AVB201.1 MS Access VBA Module 1
guest38bf
 
PPTX
OOFeatures_revised-2.pptx
ssuser84e52e
 
PPTX
object oriented programming language in c++
Ravikant517175
 
PPTX
Vendredi Tech_ la programmation fonctionnelle.pptx
Guillaume Saint Etienne
 
DOCX
Sdlc
Bilal Aslam
 
DOCX
Sdlc
Bilal Aslam
 
PDF
Top 7 Angular Best Practices to Organize Your Angular App
Katy Slemon
 
PPTX
Interaction overview and Profile UML Diagrams
Husnain Safdar
 
PDF
CSCI 383 Lecture 3 and 4: Abstraction
JI Ruan
 
PPTX
Cble assignment powerpoint activity for moodle 1
LK394
 
PDF
Bt0066 database management system2
Techglyphs
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Philip Schwarz
 
379008-rc217-functionalprogramming
Luis Atencio
 
Instant DBMS Homework Help
Database Homework Help
 
Introduction to functional programming
Thang Mai
 
GoF Design patterns I: Introduction + Structural Patterns
Sameh Deabes
 
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
Book management system
SHARDA SHARAN
 
AVB201.1 MS Access VBA Module 1
guest38bf
 
OOFeatures_revised-2.pptx
ssuser84e52e
 
object oriented programming language in c++
Ravikant517175
 
Vendredi Tech_ la programmation fonctionnelle.pptx
Guillaume Saint Etienne
 
Top 7 Angular Best Practices to Organize Your Angular App
Katy Slemon
 
Interaction overview and Profile UML Diagrams
Husnain Safdar
 
CSCI 383 Lecture 3 and 4: Abstraction
JI Ruan
 
Cble assignment powerpoint activity for moodle 1
LK394
 
Bt0066 database management system2
Techglyphs
 
Ad

More from Philip Schwarz (20)

PDF
Folding Cheat Sheet Series Titles - a series of 9 decks
Philip Schwarz
 
PDF
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
PDF
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
PDF
Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Philip Schwarz
 
PDF
The Nature of Complexity in John Ousterhout’s Philosophy of Software Design
Philip Schwarz
 
PDF
Drawing Heighway’s Dragon - Part 3 - Simplification Through Separation of Con...
Philip Schwarz
 
PDF
The Open-Closed Principle - Part 2 - The Contemporary Version - An Introduction
Philip Schwarz
 
PDF
The Open-Closed Principle - Part 1 - The Original Version
Philip Schwarz
 
PDF
Drawing Heighway’s Dragon - Part II - Recursive Function Simplification - Fro...
Philip Schwarz
 
PDF
Drawing Heighway’s Dragon - Recursive Function Rewrite - From Imperative Styl...
Philip Schwarz
 
PDF
Fibonacci Function Gallery - Part 2 - One in a series
Philip Schwarz
 
PDF
Fibonacci Function Gallery - Part 1 (of a series) - with minor corrections
Philip Schwarz
 
PDF
Fibonacci Function Gallery - Part 1 (of a series)
Philip Schwarz
 
PDF
The Debt Metaphor - Ward Cunningham in his 2009 YouTube video
Philip Schwarz
 
PDF
Folding Cheat Sheet Series Titles (so far)
Philip Schwarz
 
PDF
From Subtype Polymorphism To Typeclass-based Ad hoc Polymorphism - An Example
Philip Schwarz
 
PDF
Folding Cheat Sheet #8 - eighth in a series
Philip Schwarz
 
PDF
Function Applicative for Great Good of Leap Year Function
Philip Schwarz
 
PDF
Folding Cheat Sheet #7 - seventh in a series
Philip Schwarz
 
PDF
Folding Cheat Sheet #6 - sixth in a series
Philip Schwarz
 
Folding Cheat Sheet Series Titles - a series of 9 decks
Philip Schwarz
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
List Unfolding - 'unfold' as the Computational Dual of 'fold', and how 'unfol...
Philip Schwarz
 
Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Philip Schwarz
 
The Nature of Complexity in John Ousterhout’s Philosophy of Software Design
Philip Schwarz
 
Drawing Heighway’s Dragon - Part 3 - Simplification Through Separation of Con...
Philip Schwarz
 
The Open-Closed Principle - Part 2 - The Contemporary Version - An Introduction
Philip Schwarz
 
The Open-Closed Principle - Part 1 - The Original Version
Philip Schwarz
 
Drawing Heighway’s Dragon - Part II - Recursive Function Simplification - Fro...
Philip Schwarz
 
Drawing Heighway’s Dragon - Recursive Function Rewrite - From Imperative Styl...
Philip Schwarz
 
Fibonacci Function Gallery - Part 2 - One in a series
Philip Schwarz
 
Fibonacci Function Gallery - Part 1 (of a series) - with minor corrections
Philip Schwarz
 
Fibonacci Function Gallery - Part 1 (of a series)
Philip Schwarz
 
The Debt Metaphor - Ward Cunningham in his 2009 YouTube video
Philip Schwarz
 
Folding Cheat Sheet Series Titles (so far)
Philip Schwarz
 
From Subtype Polymorphism To Typeclass-based Ad hoc Polymorphism - An Example
Philip Schwarz
 
Folding Cheat Sheet #8 - eighth in a series
Philip Schwarz
 
Function Applicative for Great Good of Leap Year Function
Philip Schwarz
 
Folding Cheat Sheet #7 - seventh in a series
Philip Schwarz
 
Folding Cheat Sheet #6 - sixth in a series
Philip Schwarz
 

Recently uploaded (20)

PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
Become an Agentblazer Champion Challenge
Dele Amefo
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PPTX
Smart Panchayat Raj e-Governance App.pptx
Rohitnikam33
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Become an Agentblazer Champion Challenge
Dele Amefo
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Smart Panchayat Raj e-Governance App.pptx
Rohitnikam33
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
oapresentation.pptx
mehatdhavalrajubhai
 
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Presentation about variables and constant.pptx
safalsingh810
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 

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