SlideShare una empresa de Scribd logo
1 de 8
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
Jaliya Udagedara
 

La actualidad más candente (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 a Functional Effects - Part 1

379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 

Similar a 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)
 

Más de 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
 

Más de Philip Schwarz (20)

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
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

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