SlideShare a Scribd company logo
Monadic
by Mario Fusco
mario.fusco@gmail.com
twitter: @mariofusco
Fortran
C / C++
Java
Lisp
ML
Haskell
Add abstractions
C#
Algol
Subtract abstractions
Imperative languages
Functional languages
Scala
F#
Hybrid languages
Learning a new language is relatively easy
compared with learning a new paradigm.
new language < new paradigm
Functional Programming is more a new
way of thinking than a new tool set
What is a monad?

Recommended for you

Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices

The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.

Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8

Optional was introduced in Java 8 to help deal with null references in a safer way. Optional wraps an object that may or may not be present, and supports methods like map, filter, and flatMap to operate on the wrapped value in a functional style. Using Optional helps avoid NullPointerExceptions and makes it clear whether a value is present or absent, improving code readability and safety over directly using null references.

Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld

This document provides an overview of functional programming concepts and the ZIO library. It discusses the characteristics of pure functions, including being total, deterministic, and having no side effects. It contrasts functional programming with object-oriented programming. Benefits of the functional paradigm discussed include local reasoning, referential transparency, conciseness, easier testing, and support for parallel programming. The document then introduces the ZIO library, describing how it allows building resilient, asynchronous, and efficient applications using functional principles. It outlines ZIO's data type and how it represents effects.

What is a monad?
A monad is a triple (T, η, μ) where T is an endofunctor T: X → X
and η: I → T and μ: T x T → T are 2 natural transformations
satisfying these laws:
Identity law: μ(η(T)) = T = μ(T(η))
Associative law: μ(μ(T × T) × T)) = μ(T × μ(T × T))
In other words: "a monad in X is just a monoid in the category of
endofunctors of X, with product × replaced by composition of
endofunctors and unit set by the identity endofunctor"
What's the problem?
… really? do I need to know this?
In order to understand
monads you need to first
learn Cathegory Theory
In order to understand
pizza you need to first
learn Italian
… it's like saying …
… ok, so let's try to ask Google …
… no seriously, what is a monad?
A
monad
is a
structure
that puts a
value
in a
computational context

Recommended for you

Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java

Presented on 27th September 2017 to a joint meeting of 'Cork Functional Programmers' and the 'Cork Java Users Group' Based on the Kotlin Language programming course from Instil. For more details see https://instil.co/courses/kotlin-development/

programmingjavakotlin
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11

Une petite présentation sur les nouveautés de Java 9, 10 et 11 que j'ai effectuée chez un de mes clients ....

jdk9jdk10jdk11
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance

In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.

bytecodeperformancekotlin
… and why should we care about?
Reduce code duplication
Improve maintainability
Increase readability
Remove side effects
Hide complexity
Encapsulate implementation details
Allow composability
{
return flatMap( x -> unit( f.apply(x) ) );
}
Monadic Methods
M<A> unit(A a);
M<B> bind(M<A> ma, Function<A, M<B>> f);
interface M {
M<B> map(Function<A, B> f);
M<B> flatMap(Function<A, M<B>> f);
}
map can defined for every monad as
a combination of flatMap and unit
public class Person {
private Car car;
public Car getCar() { return car; }
}
public class Car {
private Insurance insurance;
public Insurance getInsurance() { return insurance; }
}
public class Insurance {
private String name;
public String getName() { return name; }
}
Finding Car's Insurance Name
String getCarInsuranceName(Person person) {
if (person != null) {
Car car = person.getCar();
if (car != null) {
Insurance insurance = car.getInsurance();
if (insurance != null) {
return insurance.getName()
}
}
}
return "Unknown";
}
Attempt 1: deep doubts

Recommended for you

The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold

This slide deck is my homage to SICP, the book which first introduced me to the Functional Programming triad of map, filter and fold. It was during my Computer Science degree that a fellow student gave me a copy of the first edition, not long after the book came out. I have not yet come across a better introduction to these three functions. The upcoming slides are closely based on the second edition of the book, a free online copy of which can be found here: https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html. Download for original image quality. Errata: slide 20: the Clojure map function is in fact the Scheme one repeated - see code below for correction. Scheme code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-scheme Clojure code: https://github.com/philipschwarz/the-fp-triad-of-map-filter-and-fold-clojure

sicpstructure and interpretation of computer programsfunctional programming
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#

The document discusses object-oriented programming concepts in C#, including defining classes, constructors, properties, static members, interfaces, inheritance, and polymorphism. It provides examples of defining a simple Cat class with fields, a constructor, properties, and methods. It also demonstrates using the Dog class by creating dog objects, setting their properties, and calling their bark method.

object-oriented programmingmethodsinheritance
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells

The document discusses principles and best practices for writing clean code, including using meaningful names, separating commands and queries, avoiding repetition, using exceptions instead of return codes, and following object-oriented principles like polymorphism instead of switch statements on objects. It provides examples of good and bad code for concepts like single responsibility, primitive obsession, and refused bequest. The overall goal is to write code that is readable, maintainable, and extendable.

clean codecode smells
Attempt 2: too many choices
String getCarInsuranceName(Person person) {
if (person == null) {
return "Unknown";
}
Car car = person.getCar();
if (car == null) {
return "Unknown";
}
Insurance insurance = car.getInsurance();
if (insurance == null) {
return "Unknown";
}
return insurance.getName()
}
What wrong with nulls?
✗
Errors source → NPE is by far the most common exception in Java
✗
Bloatware source → Worsen readability by making necessary to fill our code
with null checks
✗
Breaks Java philosophy → Java always hides pointers to developers, except
in one case: the null pointer
✗
A hole in the type system → Null has the bottom type, meaning that it can
be assigned to any reference type: this is a problem because, when
propagated to another part of the system, you have no idea what that null
was initially supposed to be
✗
Meaningless → Don't have any semantic meaning and in particular are the
wrong way to model the absence of a value in a statically typed language
“Absence of a signal should never be used as a signal“ - J. Bigalow, 1947
Tony Hoare, who invented the null reference in 1965 while working on
an object oriented language called ALGOL W, called its invention his
“billion dollar mistake”
Optional Monad to the rescue
public class Optional<T> {
private static final Optional<?> EMPTY = new Optional<>(null);
private final T value;
private Optional(T value) {
this.value = value;
}
public<U> Optional<U> map(Function<? super T, ? extends U> f) {
return value == null ? EMPTY : new Optional(f.apply(value));
}
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> f) {
return value == null ? EMPTY : f.apply(value);
}
}
public class Person {
private Optional<Car> car;
public Optional<Car> getCar() { return car; }
}
public class Car {
private Optional<Insurance> insurance;
public Optional<Insurance> getInsurance() { return insurance; }
}
public class Insurance {
private String name;
public String getName() { return name; }
}
Rethinking our model
Using the type system
to model nullable value

Recommended for you

Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#

The document provides an overview of object-oriented programming concepts in .NET such as classes, objects, methods, constructors, destructors, inheritance, polymorphism, interfaces, access modifiers, and static members. It defines each concept and provides examples to illustrate how they are implemented in C#.

c#object oriented programmingc sharp
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...

Inspired by and based on Java Language Architect Brian Goetz’s blog post: Data Oriented Programming in Java.

algebraic data typesdata oriented programmingsealed trait
Retrofit
RetrofitRetrofit
Retrofit

Retrofit is a type-safe REST client library for Android and Java that allows defining REST APIs as Java interfaces. It simplifies HTTP communication by converting remote APIs into declarative interfaces. It supports synchronous, asynchronous, and observable API consumption. The Retrofit library was created by Square.

thjugjavaandroid
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
Person
Optional
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
Person
Optional
flatMap(person -> person.getCar())
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
Optional
flatMap(person -> person.getCar())
Optional
Car

Recommended for you

Java version 11 - les 9 nouveautes
Java version 11 -  les 9 nouveautesJava version 11 -  les 9 nouveautes
Java version 11 - les 9 nouveautes

Découvrir les dernières nouveautés du Java 11

N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...

First see the problem solved using the List monad and a Scala for comprehension. Then see the Scala program translated into Haskell, both using a do expressions and using a List comprehension. Understand how the Scala for comprehension is desugared, and what role the withFilter function plays. Also understand how the Haskell do expressions and List comprehension are desugared, and what role the guard function plays. Scala code for Part 1: https://github.com/philipschwarz/n-queens-combinatorial-problem-scala-part-1 Errata: on slide 30, the resulting lists should be Haskell ones rather than Scala ones.

n-queensscalahaskell
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators

The document discusses variables and operators in Java. It defines variables as containers that store data like numbers and letters, and notes that data types determine what values can be stored. It then covers various data types including primitive types like int and float, and reference types like Strings and Arrays. The document also discusses operators like arithmetic, logical, and assignment operators. It provides examples of declaring and using variables and operators in Java code.

sunil sahusunraysjava
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
Optional
flatMap(car -> car.getInsurance())
Car
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
Optional
flatMap(car -> car.getInsurance())
Optional
Insurance
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
Optional
map(insurance -> insurance.getName())
Insurance
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
Optional
orElse("Unknown")
String

Recommended for you

Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns

Most of us use Design Patterns on a daily basis without noticing. Design patterns are commonly defined as solutions to recurring design problems. Frameworks like Laravel use Design Patterns throughout the codebase to keep structure and maintainability. In this talk we will explore the Design Patterns used in Laravel.

laraveldesign patternssoftware development
Idiomatic kotlin
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlin

The document discusses idiomatic Kotlin programming. It covers several topics including: - Using expressions idiomatically in Kotlin like if/when expressions - Examples of idiomatic patterns from the Kotlin standard library - Best practices for null safety using safe calls, let, elvis operator - Idiomatic use of classes, functions, and data classes - Leveraging the Kotlin standard library

kotlindslprogramming
MonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdfMonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdf

The document discusses monads and functional programming concepts. It begins by introducing monads and defining them mathematically. It then provides examples of monads in Java like Optional and Stream. It discusses how monads can be used to make errors, null values, and asynchronous behavior explicit in code through types. The document also shows how to create a custom Validation monad to handle errors from functions. Overall, it promotes using monads and the type system to build robust and readable functional code.

person
.flatMap(Person::getCar)
.flatMap(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");
Why map and flatMap ?
map defines monad's policy
for function application
flatMap defines monad's policy
for monads composition
This is what
happens
when you
don't use
flatMap
The Optional Monad
The Optional monad makes
the possibility of missing data
explicit
in the type system, while
hiding
the boilerplate of "if non-null" logic
Stream: another Java8 monad

Recommended for you

Monadic Java
Monadic JavaMonadic Java
Monadic Java

La teoria delle categorie sta alla programmazione funzionale come i GoF design pattern stanno a quella ad oggetti. Vista l’imminente introduzione delle lambda expression, è tempo anche per gli sviluppatori Java di imparare qualcosa in più riguardo ai più comuni pattern di programmazione funzionale. Le monadi sono probabilmente le più espressive (e forse le più incomprese) fra questi pattern, per cui lo scopo del talk è quello di introdurle, chiarendo con esempi pratici come e quando dovrebbero essere usate, sottolineando i loro vantaggi e mostrando come possono essere implementate in Java8.

codemotionmonadijava8
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8

Java 8 introduced several new features including lambda expressions, which allow functional-style programming in Java through functional interfaces containing a single abstract method, streams, which provide a way to process collections of objects in a declarative way, and default and static methods in interfaces to enable multiple inheritance. The document provides examples of using these new Java 8 features such as lambda expressions, functional interfaces, streams, and default and static methods in interfaces.

java
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer

Simple yet very effective practices which everybody, who wants to become better at writing code, should know about.

becomeprogrammerbetter
Using map & flatMap with Streams
building.getApartments().stream().
.flatMap(apartment -> apartment.getPersons().stream())
.map(Person::getName);
flatMap( -> )
StreamStream
map( -> )
StreamStream
Given n>0 find all pairs i and j
where 1 ≤ j ≤ i ≤ n and i+j is prime
Stream.iterate(1, i -> i+1).limit(n)
.flatMap(i -> Stream.iterate(1, j -> j+1).limit(n)
.map(j -> new int[]{i, j}))
.filter(pair -> isPrime(pair[0] + pair[1]))
.collect(toList());
public boolean isPrime(int n) {
return Stream.iterate(2, i -> i+1)
.limit((long) Math.sqrt(n))
.noneMatch(i -> n % i == 0);
}
The Stream Monad
The Stream monad makes
the possibility of multiple data
explicit
in the type system, while
hiding
the boilerplate of nested loops
No Monads syntactic sugar in Java :(
for { i <- List.range(1, n)
j <- List.range(1, i)
if isPrime(i + j) } yield {i, j}
List.range(1, n)
.flatMap(i =>
List.range(1, i)
.filter(j => isPrime(i+j))
.map(j => (i, j)))
Scala's for-comprehension
is just syntactic sugar to
manipulate monadstranslated by the compiler in

Recommended for you

documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...

Java 8 introduced several new features including lambda expressions, functional interfaces, and streams to support functional programming. Interfaces can now contain default and static methods to allow multiple inheritance. Streams provide a way to process collections of data elements sequentially and support parallel processing.

#java8 #lamda #streamapi
Java Class Design
Java Class DesignJava Class Design
Java Class Design

This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.

java certification preparationobject orientedjava programming
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...

by Mario Fusco - Lambdas are the main feature introduced with Java 8, but the biggest part of Java developers are still not very familliar with the most common functional idioms and patterns. The purpose of this talk is presenting with practical examples concepts like high-order functions, currying, functions composition, persistent data structures, lazy evaluation, recursion, trampolines and monoids showing how to implement them in Java and how thinking functionally can help us to design and develop more readable, reusable, performant, parallelizable and in a word better, code.

mario fuscojavalambda expression
Are there other monads
in Java8 API?
CompletableFuture
map
flatMap
Promise: a monadic CompletableFuture
public class Promise<A> implements Future<A> {
private final CompletableFuture<A> future;
private Promise(CompletableFuture<A> future) {
this.future = future;
}
public static final <A> Promise<A> promise(Supplier<A> supplier) {
return new
Promise<A>(CompletableFuture.supplyAsync(supplier));
}
public <B> Promise<B> map(Function<? super A,? extends B> f) {
return new Promise<B>(future.thenApplyAsync(f));
}
public <B> Promise<B> flatMap(Function<? super A, Promise<B>> f) {
return new Promise<B>(
future.thenComposeAsync(a -> f.apply(a).future));
}
// ... omitting methods delegating the wrapped future
}
public int slowLength(String s) {
someLongComputation();
return s.length();
}
public int slowDouble(int i) {
someLongComputation();
return i*2;
}
String s = "Hello";
Promise<Integer> p = promise(() -> slowLength(s))
.flatMap(i -> promise(() -> slowDouble(i)));
Composing long computations

Recommended for you

Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use

Lambda expressions allow passing functions as arguments and simplify anonymous classes. Functional interfaces define a single abstract method that lambda expressions or method references can implement. Default methods enable adding new methods to interfaces without breaking existing code. Streams provide a declarative way to process collections through pipelines of intermediate and terminal operations. Other new features include date/time API improvements and the Optional class for null handling.

java
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala

Short introduction to the Scala programming language which I presented on the Ebay/Marktplaats Tech Tuesday

scalaintroduction
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond

This document discusses the history and evolution of functional programming in Java, including lambda expressions and streams. It describes how lambda expressions allow passing behaviors as arguments to methods like normal data. This improves API design, opportunities for optimization, and code readability. Streams encourage a lazy, pipelined style and can execute operations in parallel. Functional idioms like immutability and pure functions help enforce correctness and isolation of side effects.

javalambdafunctional programming
The Promise Monad
The Promise monad makes
asynchronous computation
explicit
in the type system, while
hiding
the boilerplate thread logic
Creating our own Monad
Lost in Exceptions
public Person validateAge(Person p) throws ValidationException {
if (p.getAge() > 0 && p.getAge() < 130) return p;
throw new ValidationException("Age must be between 0 and 130");
}
public Person validateName(Person p) throws ValidationException {
if (Character.isUpperCase(p.getName().charAt(0))) return p;
throw new ValidationException("Name must start with uppercase");
}
List<String> errors = new ArrayList<String>();
try {
validateAge(person);
} catch (ValidationException ex) {
errors.add(ex.getMessage());
}
try {
validateName(person);
} catch (ValidationException ex) {
errors.add(ex.getMessage());
}
public abstract class Validation<L, A> {
protected final A value;
private Validation(A value) {
this.value = value;
}
public abstract <B> Validation<L, B> map(
Function<? super A, ? extends B> mapper);
public abstract <B> Validation<L, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper);
public abstract boolean isSuccess();
}
Defining a Validation Monad

Recommended for you

What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7

A lap around the new features in C# 7. For a better experience, go to https://docs.com/paulo-morgado/9635/what-s-new-in-c-7

c#c# 7programar2017
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy

This document discusses parallel programming tools in Java. It covers the Fork/Join framework and Parallel Arrays API introduced in JDK 6 and 7. It also discusses stream parallelism introduced in JDK 8 for parallel collection processing. Some performance caveats of parallel programming discussed include lack of associativity and potential overhead of parallelization. Examples shown include parallel sorting of large lists and parallel reduction of stream elements.

lambdasjdk 8parallel computing
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript

The document discusses object-oriented programming concepts in TypeScript such as classes, inheritance, polymorphism, and mixins. It provides code examples of implementing interfaces and classes to demonstrate inheritance and composition. Mixins are discussed as a way to reuse behavior across class hierarchies by applying multiple base classes to a derived class using a mixin function. The examples show how to define mixin behaviors as classes and apply them to implementing classes to achieve multiple inheritance in TypeScript.

ooptypescript
Success !!!
public class Success<L, A> extends Validation<L, A> {
private Success(A value) { super(value); }
public <B> Validation<L, B> map(
Function<? super A, ? extends B> mapper) {
return success(mapper.apply(value));
}
public <B> Validation<L, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
return (Validation<L, B>) mapper.apply(value);
}
public boolean isSuccess() { return true; }
public static <L, A> Success<L, A> success(A value) {
return new Success<L, A>(value);
}
}
Failure :(((
public class Failure<L, A> extends Validation<L, A> {
protected final L left;
public Failure(A value, L left) {super(value); this.left = left;}
public <B> Validation<L, B> map(
Function<? super A, ? extends B> mapper) {
return failure(left, mapper.apply(value));
}
public <B> Validation<L, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
Validation<?, ? extends B> result = mapper.apply(value);
return result.isSuccess() ?
failure(left, result.value) :
failure(((Failure<L, B>)result).left, result.value);
}
public boolean isSuccess() { return false; }
}
The Validation Monad
The Validation monad makes
the possibility of errors
explicit
in the type system, while
hiding
the boilerplate of "try/catch" logic
Rewriting validating methods
public Validation<String, Person> validateAge(Person p) {
return (p.getAge() > 0 && p.getAge() < 130) ?
success(p) :
failure("Age must be between 0 and 130", p);
}
public Validation<String, Person> validateName(Person p) {
return Character.isUpperCase(p.getName().charAt(0)) ?
success(p) :
failure("Name must start with uppercase", p);
}

Recommended for you

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой

This document provides an overview of functional programming concepts for object-oriented programmers. It discusses the fundamentals of FP including immutability, purity, first-class and higher-order functions, closures, and recursion. It provides examples of these concepts in languages like Lisp, F#, C#, and JavaScript. The document also compares OO and FP concepts and discusses derived FP concepts like partial application, lazy evaluation, and pattern matching.

#softwaredevelopment#software#development
Exam2prep
Exam2prepExam2prep
Exam2prep

The program defines a Car class with private String and double variables for model and price. It includes getter and setter methods for these variables. It constructs a Car object, sets its model and price using the setter methods, then prints the model and price using the getter methods. Between setting and getting, it checks if the price could be changed by calling the setter and printing a message if it returns false.

Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan

Workshop for JCConf - http://jcconf.tw/2016/ Java Community Conference Taiwan - https://www.facebook.com/jcconf Scala Taiwan - https://gitter.im/ScalaTaiwan/ScalaTaiwan Scala Taiwan Meetup - http://www.meetup.com/Scala-Taiwan-Meetup/ 1. Why Scala? 2. Scala concept 3. Program with Scala? 4. Imperative 5. Object-Oriented 6. Functional 7. Collections 8. Summary of Scala 9. Further Reading & Reference

scalatutorialintroduction
Lesson learned:
Leverage the Type System
Gathering multiple errors - Success
public class SuccessList<L, A> extends Success<List<L>, A> {
public SuccessList(A value) { super(value); }
public <B> Validation<List<L>, B> map(
Function<? super A, ? extends B> mapper) {
return new SuccessList(mapper.apply(value));
}
public <B> Validation<List<L>, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
Validation<?, ? extends B> result = mapper.apply(value);
return (Validation<List<L>, B>)(result.isSuccess() ?
new SuccessList(result.value) :
new FailureList<L, B>(((Failure<L, B>)result).left,
result.value));
}
}
Gathering multiple errors - Failure
public class FailureList<L, A> extends Failure<List<L>, A> {
private FailureList(List<L> left, A value) { super(left, value); }
public <B> Validation<List<L>, B> map(
Function<? super A, ? extends B> mapper) {
return new FailureList(left, mapper.apply(value));
}
public <B> Validation<List<L>, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
Validation<?, ? extends B> result = mapper.apply(value);
return (Validation<List<L>, B>)(result.isSuccess() ?
new FailureList(left, result.value) :
new FailureList<L, B>(new ArrayList<L>(left) {{
add(((Failure<L, B>)result).left);
}}, result.value));
}
}
Monadic Validation
Validation<List<String>, Person>
validatedPerson = success(person).failList()
.flatMap(Validator::validAge)
.flatMap(Validator::validName);

Recommended for you

‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance

Object Oriented Programming_Chapter 3 (Two Lectures) 1- Let’s think on Inheritance 2- Let’s focus on Superclass’s Constructor الكلية الجامعية للعلوم والتكنولوجيا - خان يونس University college of science & technology

inheritancesuperclasssubclass
06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt

This document discusses methods in Java programming. It defines methods as collections of statements grouped together to perform operations. Methods can take parameters and return values. When a method is invoked, an activation record is created on the call stack to store its parameters and variables. The document discusses defining methods, passing arguments, return values, and method overloading. It also provides examples of tracing method calls and return values on the call stack.

E6
E6E6
E6

This document contains solutions to exam problems related to recursion, induction, and object-oriented programming concepts in Java. It includes code for recursive methods to reverse a Word class, a proof of correctness for the reverse method using structural induction, code for Instrument, StringInstrument and PercussionInstrument classes in an inheritance hierarchy, and short answers explaining concepts like encapsulation, access modifiers, and abstract classes and methods.

Homework: develop your own
Transaction Monad
The Transaction monad makes
transactionally
explicit
in the type system, while
hiding
the boilerplate propagation of invoking rollbacks
Alternative Monads Definitions
Monads are parametric types with two operations
flatMap and unit that obey some algebraic laws
Monads are structures that represent
computations defined as sequences of steps
Monads are chainable containers types that confine
values defining how to transform and combine them
Monads are return types that
guide you through the happy path
Functional Domain Design
A practical example
A OOP BankAccount ...
public class Balance {
final BigDecimal amount;
public Balance( BigDecimal amount ) { this.amount = amount; }
}
public class Account {
private final String owner;
private final String number;
private Balance balance = new Balance(BigDecimal.ZERO);
public Account( String owner, String number ) {
this.owner = owner;
this.number = number;
}
public void credit(BigDecimal value) {
balance = new Balance( balance.amount.add( value ) );
}
public void debit(BigDecimal value) throws InsufficientBalanceException {
if (balance.amount.compareTo( value ) < 0)
throw new InsufficientBalanceException();
balance = new Balance( balance.amount.subtract( value ) );
}
}
Mutability
Error handling
using Exception

Recommended for you

Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP

The document discusses defining and using methods in Java. It defines what a method is and its key components like the method signature, return type, parameters, and body. It then demonstrates a sample max method to return the maximum of two numbers and traces the steps of invoking the method from the main method, including passing arguments, executing the method body, and returning the result. The document aims to explain the basics of methods in Java, including how to define reusable methods and invoke them to perform certain tasks.

methodjava
Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation

The document discusses business automation in the cloud using Kogito. It begins with an introduction to business automation concepts like processes, rules, and workflows. It then provides an overview of Kogito, describing it as a cloud-native development, deployment and execution platform for business automation that uses technologies like Drools, jBPM, and Quarkus under the hood. The document also demonstrates a sample serverless workflow built with Kogito.

cloud computingkogitobusiness automation
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...

Mario Fusco discusses turning old Java rule engine projects into serverless components by refactoring them to run natively on GraalVM and integrate with Quarkus. He describes the limitations of ahead-of-time compilation with GraalVM, such as lack of dynamic classloading. He details refactoring Drools to use an executable model and removing dependencies on dynamic class definition. This allows Drools to natively compile on GraalVM. He also discusses integrating the refactored Drools with Quarkus.

microservicesgraalvmdrools
… and how we can use it
Account a = new Account("Alice", "123");
Account b = new Account("Bob", "456");
Account c = new Account("Charlie", "789");
List<Account> unpaid = new ArrayList<>();
for (Account account : Arrays.asList(a, b, c)) {
try {
account.debit( new BigDecimal( 100.00 ) );
} catch (InsufficientBalanceException e) {
unpaid.add(account);
}
}
List<Account> unpaid = new ArrayList<>();
Stream.of(a, b, c).forEach( account -> {
try {
account.debit( new BigDecimal( 100.00 ) );
} catch (InsufficientBalanceException e) {
unpaid.add(account);
}
} );
Mutation of enclosing scope
Cannot use a parallel Stream
Ugly syntax
Error handling with Try monad
public interface Try<A> {
<B> Try<B> map(Function<A, B> f);
<B> Try<B> flatMap(Function<A, Try<B>> f);
boolean isFailure();
}
public Success<A> implements Try<A> {
private final A value;
public Success(A value) { this.value = value; }
public boolean isFailure() { return false; }
public <B> Try<B> map(Function<A, B> f) {
return new Success<>(f.apply(value));
}
public <B> Try<B> flatMap(Function<A, Try<B>> f) {
return f.apply(value);
}
}
public Failure<A> implements Try<T> {
private final Object error;
public Failure(Object error) { this.error = error; }
public boolean isFailure() { return false; }
public <B> Try<B> map(Function<A, B> f) { return (Failure<B>)this; }
public <B> Try<B> flatMap(Function<A, Try<B>> f) { return (Failure<B>)this; }
}
A functional BankAccount ...
public class Account {
private final String owner;
private final String number;
private final Balance balance;
public Account( String owner, String number, Balance balance ) {
this.owner = owner;
this.number = number;
this.balance = balance;
}
public Account credit(BigDecimal value) {
return new Account( owner, number,
new Balance( balance.amount.add( value ) ) );
}
public Try<Account> debit(BigDecimal value) {
if (balance.amount.compareTo( value ) < 0)
return new Failure<>( new InsufficientBalanceError() );
return new Success<>(
new Account( owner, number,
new Balance( balance.amount.subtract( value ) ) ) );
}
}
Immutable
Error handling
without Exceptions
… and how we can use it
Account a = new Account("Alice", "123");
Account b = new Account("Bob", "456");
Account c = new Account("Charlie", "789");
List<Account> unpaid =
Stream.of( a, b, c )
.map( account ->
new Tuple2<>( account,
account.debit( new BigDecimal( 100.00 ) ) ) )
.filter( t -> t._2.isFailure() )
.map( t -> t._1 )
.collect( toList() );
List<Account> unpaid =
Stream.of( a, b, c )
.filter( account ->
account.debit( new BigDecimal( 100.00 ) )
.isFailure() )
.collect( toList() );

Recommended for you

OOP and FP
OOP and FPOOP and FP
OOP and FP

The document discusses object-oriented programming (OOP) and functional programming (FP). It argues that OOP and FP are not opposites and can be effectively combined. It addresses common myths about FP, such as that it is new, hard, or only suitable for mathematical problems. The document also compares how OOP and FP approach concepts like decomposition, composition, error handling, and mutability/referential transparency. While both approaches have merits, the document concludes there is no single best approach and the choice depends on the problem and programmer preferences.

object oriented programmingfunctional programmingdesign pattern
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive

The document provides an overview of key features and internals of the Drools 6 rule engine, including: - The Phreak algorithm, which is faster than ReteOO and uses set-based propagation for improved performance on large data sets. - The deployment model which uses kjar modules that are self-contained, versioned JAR files containing rules, models, and configuration. This allows for incremental compilation and use of the KieScanner for automatic updates. - Changes to type declarations which are now compiled into the kjar, allowing them to be used directly in Java code without reflection.

drools
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer

The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8

functional programmingobject oriented programminglambda
From Methods to Functions
public class BankService {
public static Try<Account> open(String owner, String number,
BigDecimal balance) {
if (initialBalance.compareTo( BigDecimal.ZERO ) < 0)
return new Failure<>( new InsufficientBalanceError() );
return new Success<>( new Account( owner, number,
new Balance( balance ) ) );
}
public static Account credit(Account account, BigDecimal value) {
return new Account( account.owner, account.number,
new Balance( account.balance.amount.add( value ) ) );
}
public static Try<Account> debit(Account account, BigDecimal value) {
if (account.balance.amount.compareTo( value ) < 0)
return new Failure<>( new InsufficientBalanceError() );
return new Success<>(
new Account( account.owner, account.number,
new Balance( account.balance.amount.subtract( value ) ) ) );
}
}
Decoupling state and behavior
import static BankService.*
Try<Account> account =
open( "Alice", "123", new BigDecimal( 100.00 ) )
.map( acc -> credit( acc, new BigDecimal( 200.00 ) ) )
.map( acc -> credit( acc, new BigDecimal( 300.00 ) ) )
.flatMap( acc -> debit( acc, new BigDecimal( 400.00 ) ) );
The object-oriented paradigm couples state and behavior
Functional programming decouples them
… but I need a BankConnection!
What about dependency injection?
A naïve solution
public class BankService {
public static Try<Account> open(String owner, String number,
BigDecimal balance, BankConnection bankConnection) {
...
}
public static Account credit(Account account, BigDecimal value,
BankConnection bankConnection) {
...
}
public static Try<Account> debit(Account account, BigDecimal value,
BankConnection bankConnection) {
...
}
}
BankConnection bconn = new BankConnection();
Try<Account> account =
open( "Alice", "123", new BigDecimal( 100.00 ), bconn )
.map( acc -> credit( acc, new BigDecimal( 200.00 ), bconn ) )
.map( acc -> credit( acc, new BigDecimal( 300.00 ), bconn ) )
.flatMap( acc -> debit( acc, new BigDecimal( 400.00 ), bconn ) );
Necessary to create the
BankConnection in advance ...
… and pass it to all methods

Recommended for you

Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...

Reactive Programming for a demanding world: building event-driven and responsive applications with RxJava

eventsrxjavareactive programming
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM

This document compares different concurrency models on the JVM, including the native Java concurrency model based on threads, semaphores, and locks. It discusses the pros and cons of threads and locks, including issues around non-determinism from shared mutable state. Functional programming with immutable data and internal iteration is presented as an alternative that allows for free parallelism. The document also covers actors and their message passing approach, as well as software transactional memory.

parallelismconcurrencythreads
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming

The document discusses several key concepts in functional programming including: 1) Pure functions that are referentially transparent and have no side effects like modifying variables or data structures. 2) Immutable data and persistent data structures that allow for sharing without synchronization. 3) Separating computational logic from side effects improves modularity and allows for parallelization. 4) A pure functional core can be wrapped with functions that have side effects to push effects to the outer layers.

functional programming
Making it lazy
public class BankService {
public static Function<BankConnection, Try<Account>>
open(String owner, String number, BigDecimal balance) {
return (BankConnection bankConnection) -> ...
}
public static Function<BankConnection, Account>
credit(Account account, BigDecimal value) {
return (BankConnection bankConnection) -> ...
}
public static Function<BankConnection, Try<Account>>
debit(Account account, BigDecimal value) {
return (BankConnection bankConnection) -> ...
}
}
Function<BankConnection, Try<Account>> f =
(BankConnection conn) ->
open( "Alice", "123", new BigDecimal( 100.00 ) )
.apply( conn )
.map( acc -> credit( acc, new BigDecimal( 200.00 ) ).apply( conn ) )
.map( acc -> credit( acc, new BigDecimal( 300.00 ) ).apply( conn ) )
.flatMap( acc -> debit( acc, new BigDecimal( 400.00 ) ).apply( conn ) );
Try<Account> account = f.apply( new BankConnection() );
open
Ctx -> S1
S1
A, B
credit
Ctx
S2
C, D
result
open
S1
A, B, Ctx
injection
credit
C, D, Ctx, S1
resultS2
Pure OOP implementation Static Methods
open
A, B
apply(Ctx)
S1
Ctx -> S2
apply(Ctx)
S2
C, D
Lazy evaluation
Ctx
credit
result
Introducing the Reader monad ...
public class Reader<R, A> {
private final Function<R, A> run;
public Reader( Function<R, A> run ) {
this.run = run;
}
public <B> Reader<R, B> map(Function<A, B> f) {
...
}
public <B> Reader<R, B> flatMap(Function<A, Reader<R, B>> f) {
...
}
public A apply(R r) {
return run.apply( r );
}
}
The reader monad provides an environment to
wrap an abstract computation without evaluating it
Introducing the Reader monad ...
public class Reader<R, A> {
private final Function<R, A> run;
public Reader( Function<R, A> run ) {
this.run = run;
}
public <B> Reader<R, B> map(Function<A, B> f) {
return new Reader<>((R r) -> f.apply( apply( r ) ));
}
public <B> Reader<R, B> flatMap(Function<A, Reader<R, B>> f) {
return new Reader<>((R r) -> f.apply( apply( r ) ).apply( r ));
}
public A apply(R r) {
return run.apply( r );
}
}
The reader monad provides an environment to
wrap an abstract computation without evaluating it

Recommended for you

Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language

This document discusses domain specific languages (DSLs). It defines a DSL as a computer programming language with limited expressiveness focused on a particular domain to improve communication. The document discusses why DSLs are used to improve communication and maintainability. It also covers different types of DSLs, including internal and external DSLs. Examples of DSLs like Hibernate queries, jMock, and lambdaj are provided to illustrate DSL design patterns.

java dsl
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools

Drools was created as a rule engine but has expanded to become a business modeling platform through the integration of business rule management, business process management, and complex event processing. It achieves this through modules like Drools Expert (rules), Drools Flow (processes), Drools Fusion (events), and Drools Planner (planning). Drools Guvnor provides a centralized repository for managing knowledge bases. The platform uses a declarative approach to represent business logic and processes through rules, events, and planning constraints.

drools
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward

The document summarizes new features in Java 7-8 including lambda expressions, switch on strings, try-with-resources, and the fork/join framework. Java 8 will focus on lambda expressions to provide functional programming capabilities and default methods to allow interfaces to have default implementations without breaking existing implementations. Java 9 may include additional modularization support.

javacoinlambda
The Reader Monad
The Reader monad makes
a lazy computation
explicit
in the type system, while
hiding
the logic to apply it
In other words the reader monad
allows us to treat functions as
values with a context
We can act as if we already know
what the functions will return.
… and combining it with Try
public class TryReader<R, A> {
private final Function<R, Try<A>> run;
public TryReader( Function<R, Try<A>> run ) {
this.run = run;
}
public <B> TryReader<R, B> map(Function<A, B> f) {
...
}
public <B> TryReader<R, B> mapReader(Function<A, Reader<R, B>> f) {
...
}
public <B> TryReader<R, B> flatMap(Function<A, TryReader<R, B>> f) {
...
}
public Try<A> apply(R r) {
return run.apply( r );
}
}
… and combining it with Try
public class TryReader<R, A> {
private final Function<R, Try<A>> run;
public TryReader( Function<R, Try<A>> run ) {
this.run = run;
}
public <B> TryReader<R, B> map(Function<A, B> f) {
return new TryReader<R, B>((R r) -> apply( r )
.map( a -> f.apply( a ) ));
}
public <B> TryReader<R, B> mapReader(Function<A, Reader<R, B>> f) {
return new TryReader<R, B>((R r) -> apply( r )
.map( a -> f.apply( a ).apply( r ) ));
}
public <B> TryReader<R, B> flatMap(Function<A, TryReader<R, B>> f) {
return new TryReader<R, B>((R r) -> apply( r )
.flatMap( a -> f.apply( a ).apply( r ) ));
}
public Try<A> apply(R r) {
return run.apply( r );
}
}
A more user-friendly API
public class BankService {
public static TryReader<BankConnection, Account>
open(String owner, String number, BigDecimal balance) {
return new TryReader<>( (BankConnection bankConnection) -> ... )
}
public static Reader<BankConnection, Account>
credit(Account account, BigDecimal value) {
return new Reader<>( (BankConnection bankConnection) -> ... )
}
public static TryReader<BankConnection, Account>
debit(Account account, BigDecimal value) {
return new TryReader<>( (BankConnection bankConnection) -> ... )
}
}
TryReader<BankConnection, Account> reader =
open( "Alice", "123", new BigDecimal( 100.00 ) )
.mapReader( acc -> credit( acc, new BigDecimal( 200.00 ) ) )
.mapReader( acc -> credit( acc, new BigDecimal( 300.00 ) ) )
.flatMap( acc -> debit( acc, new BigDecimal( 400.00 ) ) );
Try<Account> account = reader.apply( new BankConnection() );

Recommended for you

Hammurabi
HammurabiHammurabi
Hammurabi

Hammurabi is an internal domain-specific language (DSL) for rule-based programming implemented in Scala. It allows domain experts to write rules in plain Scala code without learning a new language. Rules are evaluated by a rule engine that executes matching rules on a working memory of facts. The DSL aims to be readable, flexible and leverage Scala features like autocompletion. It also supports priorities, selecting objects, and exiting or failing evaluation. The architecture uses actors for concurrent rule evaluation. Future work includes improving performance using RETE algorithm and providing alternative selection methods.

Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring

This document summarizes Spring features for building loosely coupled, maintainable applications. It discusses how Spring promotes loose coupling through dependency injection and application events. It also describes how to implement workflows with jBPM and manage transactions declaratively in Spring.

aopspringjava
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj

Lambdaj is an internal DSL that allows manipulating collections without loops. It provides static methods to filter, sort, extract, and otherwise operate on collections. By treating collections as single objects and allowing method references, lambdaj can concisely represent operations that would otherwise require loops. While lambdaj is generally 4-6 times slower than iterative versions, it improves readability of collection operations.

collectionsclosuresjava
open
Ctx -> S1
S1
A, B
credit
Ctx
S2
C, D
result
open
S1
A, B, Ctx
injection
credit
C, D, Ctx, S1
resultS2
Pure OOP implementation Static Methods
open
A, B
apply(Ctx)
S1
Ctx -> S2
apply(Ctx)
S2
C, D
Lazy evaluation
Ctx
credit
Reader monad
result
Ctx -> S1
A, B C, D
map(credit)
Ctx -> result
apply(Ctx)
open
Ctx -> S2
To recap: a Monad is a design
patternAlias
 flatMap that shit
Intent
 Put a value in a computational context defining the policy
on how to operate on it
Motivations
 Reduce code duplication
 Improve maintainability
 Increase readability
 Remove side effects
 Hide complexity
 Encapusalate implementation details
 Allow composability
Known Uses
 Optional, Stream, Promise, Validation, Transaction, State, …
Use Monads whenever possible
to keep your code clean and
encapsulate repetitive logic
TL;DR
Monadic Java

Recommended for you

Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM

This document discusses concurrency, scalability, and fault tolerance using actors and software transactional memory (STM) in Akka. It describes how actors provide message-passing concurrency by isolating processes and avoiding shared state. Actors allow easy reasoning about concurrency by preventing issues like race conditions and deadlocks. The document also covers how Akka implements actors, typed actors, remote actors, supervisor hierarchies for fault tolerance, and STM for coordinating concurrent changes to shared state transactionally. Combining actors with STM results in "transactors" that allow building distributed, concurrent, and fault-tolerant applications.

actorsstmconcurrency
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet

The document provides an overview of a two-day training course on Scala that covers topics like object orientation, functional programming, pattern matching, generics, traits, case classes, tuples, collections, concurrency, options and monads. The course aims to show how Scala combines object-oriented and functional programming approaches and provides examples of commonly used Scala features like classes, traits, pattern matching, generics and collections.

scala
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses

CIO Council Cal Poly Humboldt September 22, 2023

national research platformdistributed supercomputerdistributed systems
Mario Fusco
Red Hat – Senior Software Engineer
mario.fusco@gmail.com
twitter: @mariofusco
Q A
Thanks … Questions?

More Related Content

What's hot

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
Mario Fusco
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
Philip Schwarz
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
John Ferguson Smart Limited
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
Richard Walker
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Jorge Vásquez
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
Garth Gilmour
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
Mahamadou TOURE, Ph.D.
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
intelliyole
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
Philip Schwarz
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
Mario Sangiorgio
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
foreverredpb
 
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
 
Retrofit
RetrofitRetrofit
Retrofit
Amin Cheloh
 
Java version 11 - les 9 nouveautes
Java version 11 -  les 9 nouveautesJava version 11 -  les 9 nouveautes
Java version 11 - les 9 nouveautes
Abdenour Bouateli
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
Philip Schwarz
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
Bobby Bouwmann
 
Idiomatic kotlin
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlin
Anton Arhipov
 

What's hot (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
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...
 
Retrofit
RetrofitRetrofit
Retrofit
 
Java version 11 - les 9 nouveautes
Java version 11 -  les 9 nouveautesJava version 11 -  les 9 nouveautes
Java version 11 - les 9 nouveautes
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
Idiomatic kotlin
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlin
 

Similar to Monadic Java

MonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdfMonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdf
EonisGonzara1
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
Codemotion
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus Pöial
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
Akaks
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Codemotion
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Peter Maas
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
José Paumard
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Exam2prep
Exam2prepExam2prep
Exam2prep
Aditya Parakh
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
Mahmoud Alfarra
 
06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
RohitNukte
 
E6
E6E6
E6
lksoo
 
Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
Khirulnizam Abd Rahman
 

Similar to Monadic Java (20)

MonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdfMonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdf
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Exam2prep
Exam2prepExam2prep
Exam2prep
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
 
E6
E6E6
E6
 
Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
 

More from Mario Fusco

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
Mario Fusco
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
Mario Fusco
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
Mario Fusco
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
Mario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
Mario Fusco
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
Mario Fusco
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
Mario Fusco
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
Mario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Hammurabi
HammurabiHammurabi
Hammurabi
Mario Fusco
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
Mario Fusco
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
Mario Fusco
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 

More from Mario Fusco (16)

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 

Recently uploaded

The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
Matthew Sinclair
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
Measuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at TwitterMeasuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at Twitter
ScyllaDB
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
Matthew Sinclair
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
Bert Blevins
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 

Recently uploaded (20)

The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
Measuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at TwitterMeasuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at Twitter
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 

Monadic Java

  • 2. Fortran C / C++ Java Lisp ML Haskell Add abstractions C# Algol Subtract abstractions Imperative languages Functional languages Scala F# Hybrid languages
  • 3. Learning a new language is relatively easy compared with learning a new paradigm. new language < new paradigm Functional Programming is more a new way of thinking than a new tool set
  • 4. What is a monad?
  • 5. What is a monad? A monad is a triple (T, η, μ) where T is an endofunctor T: X → X and η: I → T and μ: T x T → T are 2 natural transformations satisfying these laws: Identity law: μ(η(T)) = T = μ(T(η)) Associative law: μ(μ(T × T) × T)) = μ(T × μ(T × T)) In other words: "a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor" What's the problem?
  • 6. … really? do I need to know this? In order to understand monads you need to first learn Cathegory Theory In order to understand pizza you need to first learn Italian … it's like saying …
  • 7. … ok, so let's try to ask Google …
  • 8. … no seriously, what is a monad? A monad is a structure that puts a value in a computational context
  • 9. … and why should we care about? Reduce code duplication Improve maintainability Increase readability Remove side effects Hide complexity Encapsulate implementation details Allow composability
  • 10. { return flatMap( x -> unit( f.apply(x) ) ); } Monadic Methods M<A> unit(A a); M<B> bind(M<A> ma, Function<A, M<B>> f); interface M { M<B> map(Function<A, B> f); M<B> flatMap(Function<A, M<B>> f); } map can defined for every monad as a combination of flatMap and unit
  • 11. public class Person { private Car car; public Car getCar() { return car; } } public class Car { private Insurance insurance; public Insurance getInsurance() { return insurance; } } public class Insurance { private String name; public String getName() { return name; } } Finding Car's Insurance Name
  • 12. String getCarInsuranceName(Person person) { if (person != null) { Car car = person.getCar(); if (car != null) { Insurance insurance = car.getInsurance(); if (insurance != null) { return insurance.getName() } } } return "Unknown"; } Attempt 1: deep doubts
  • 13. Attempt 2: too many choices String getCarInsuranceName(Person person) { if (person == null) { return "Unknown"; } Car car = person.getCar(); if (car == null) { return "Unknown"; } Insurance insurance = car.getInsurance(); if (insurance == null) { return "Unknown"; } return insurance.getName() }
  • 14. What wrong with nulls? ✗ Errors source → NPE is by far the most common exception in Java ✗ Bloatware source → Worsen readability by making necessary to fill our code with null checks ✗ Breaks Java philosophy → Java always hides pointers to developers, except in one case: the null pointer ✗ A hole in the type system → Null has the bottom type, meaning that it can be assigned to any reference type: this is a problem because, when propagated to another part of the system, you have no idea what that null was initially supposed to be ✗ Meaningless → Don't have any semantic meaning and in particular are the wrong way to model the absence of a value in a statically typed language “Absence of a signal should never be used as a signal“ - J. Bigalow, 1947 Tony Hoare, who invented the null reference in 1965 while working on an object oriented language called ALGOL W, called its invention his “billion dollar mistake”
  • 15. Optional Monad to the rescue public class Optional<T> { private static final Optional<?> EMPTY = new Optional<>(null); private final T value; private Optional(T value) { this.value = value; } public<U> Optional<U> map(Function<? super T, ? extends U> f) { return value == null ? EMPTY : new Optional(f.apply(value)); } public<U> Optional<U> flatMap(Function<? super T, Optional<U>> f) { return value == null ? EMPTY : f.apply(value); } }
  • 16. public class Person { private Optional<Car> car; public Optional<Car> getCar() { return car; } } public class Car { private Optional<Insurance> insurance; public Optional<Insurance> getInsurance() { return insurance; } } public class Insurance { private String name; public String getName() { return name; } } Rethinking our model Using the type system to model nullable value
  • 17. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity
  • 18. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity Person Optional
  • 19. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity Person Optional flatMap(person -> person.getCar())
  • 20. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity Optional flatMap(person -> person.getCar()) Optional Car
  • 21. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity Optional flatMap(car -> car.getInsurance()) Car
  • 22. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity Optional flatMap(car -> car.getInsurance()) Optional Insurance
  • 23. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity Optional map(insurance -> insurance.getName()) Insurance
  • 24. String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Restoring the sanity Optional orElse("Unknown") String
  • 25. person .flatMap(Person::getCar) .flatMap(Car::getInsurance) .map(Insurance::getName) .orElse("Unknown"); Why map and flatMap ? map defines monad's policy for function application flatMap defines monad's policy for monads composition
  • 26. This is what happens when you don't use flatMap
  • 27. The Optional Monad The Optional monad makes the possibility of missing data explicit in the type system, while hiding the boilerplate of "if non-null" logic
  • 29. Using map & flatMap with Streams building.getApartments().stream(). .flatMap(apartment -> apartment.getPersons().stream()) .map(Person::getName); flatMap( -> ) StreamStream map( -> ) StreamStream
  • 30. Given n>0 find all pairs i and j where 1 ≤ j ≤ i ≤ n and i+j is prime Stream.iterate(1, i -> i+1).limit(n) .flatMap(i -> Stream.iterate(1, j -> j+1).limit(n) .map(j -> new int[]{i, j})) .filter(pair -> isPrime(pair[0] + pair[1])) .collect(toList()); public boolean isPrime(int n) { return Stream.iterate(2, i -> i+1) .limit((long) Math.sqrt(n)) .noneMatch(i -> n % i == 0); }
  • 31. The Stream Monad The Stream monad makes the possibility of multiple data explicit in the type system, while hiding the boilerplate of nested loops
  • 32. No Monads syntactic sugar in Java :( for { i <- List.range(1, n) j <- List.range(1, i) if isPrime(i + j) } yield {i, j} List.range(1, n) .flatMap(i => List.range(1, i) .filter(j => isPrime(i+j)) .map(j => (i, j))) Scala's for-comprehension is just syntactic sugar to manipulate monadstranslated by the compiler in
  • 33. Are there other monads in Java8 API?
  • 35. Promise: a monadic CompletableFuture public class Promise<A> implements Future<A> { private final CompletableFuture<A> future; private Promise(CompletableFuture<A> future) { this.future = future; } public static final <A> Promise<A> promise(Supplier<A> supplier) { return new Promise<A>(CompletableFuture.supplyAsync(supplier)); } public <B> Promise<B> map(Function<? super A,? extends B> f) { return new Promise<B>(future.thenApplyAsync(f)); } public <B> Promise<B> flatMap(Function<? super A, Promise<B>> f) { return new Promise<B>( future.thenComposeAsync(a -> f.apply(a).future)); } // ... omitting methods delegating the wrapped future }
  • 36. public int slowLength(String s) { someLongComputation(); return s.length(); } public int slowDouble(int i) { someLongComputation(); return i*2; } String s = "Hello"; Promise<Integer> p = promise(() -> slowLength(s)) .flatMap(i -> promise(() -> slowDouble(i))); Composing long computations
  • 37. The Promise Monad The Promise monad makes asynchronous computation explicit in the type system, while hiding the boilerplate thread logic
  • 39. Lost in Exceptions public Person validateAge(Person p) throws ValidationException { if (p.getAge() > 0 && p.getAge() < 130) return p; throw new ValidationException("Age must be between 0 and 130"); } public Person validateName(Person p) throws ValidationException { if (Character.isUpperCase(p.getName().charAt(0))) return p; throw new ValidationException("Name must start with uppercase"); } List<String> errors = new ArrayList<String>(); try { validateAge(person); } catch (ValidationException ex) { errors.add(ex.getMessage()); } try { validateName(person); } catch (ValidationException ex) { errors.add(ex.getMessage()); }
  • 40. public abstract class Validation<L, A> { protected final A value; private Validation(A value) { this.value = value; } public abstract <B> Validation<L, B> map( Function<? super A, ? extends B> mapper); public abstract <B> Validation<L, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper); public abstract boolean isSuccess(); } Defining a Validation Monad
  • 41. Success !!! public class Success<L, A> extends Validation<L, A> { private Success(A value) { super(value); } public <B> Validation<L, B> map( Function<? super A, ? extends B> mapper) { return success(mapper.apply(value)); } public <B> Validation<L, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { return (Validation<L, B>) mapper.apply(value); } public boolean isSuccess() { return true; } public static <L, A> Success<L, A> success(A value) { return new Success<L, A>(value); } }
  • 42. Failure :((( public class Failure<L, A> extends Validation<L, A> { protected final L left; public Failure(A value, L left) {super(value); this.left = left;} public <B> Validation<L, B> map( Function<? super A, ? extends B> mapper) { return failure(left, mapper.apply(value)); } public <B> Validation<L, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { Validation<?, ? extends B> result = mapper.apply(value); return result.isSuccess() ? failure(left, result.value) : failure(((Failure<L, B>)result).left, result.value); } public boolean isSuccess() { return false; } }
  • 43. The Validation Monad The Validation monad makes the possibility of errors explicit in the type system, while hiding the boilerplate of "try/catch" logic
  • 44. Rewriting validating methods public Validation<String, Person> validateAge(Person p) { return (p.getAge() > 0 && p.getAge() < 130) ? success(p) : failure("Age must be between 0 and 130", p); } public Validation<String, Person> validateName(Person p) { return Character.isUpperCase(p.getName().charAt(0)) ? success(p) : failure("Name must start with uppercase", p); }
  • 46. Gathering multiple errors - Success public class SuccessList<L, A> extends Success<List<L>, A> { public SuccessList(A value) { super(value); } public <B> Validation<List<L>, B> map( Function<? super A, ? extends B> mapper) { return new SuccessList(mapper.apply(value)); } public <B> Validation<List<L>, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { Validation<?, ? extends B> result = mapper.apply(value); return (Validation<List<L>, B>)(result.isSuccess() ? new SuccessList(result.value) : new FailureList<L, B>(((Failure<L, B>)result).left, result.value)); } }
  • 47. Gathering multiple errors - Failure public class FailureList<L, A> extends Failure<List<L>, A> { private FailureList(List<L> left, A value) { super(left, value); } public <B> Validation<List<L>, B> map( Function<? super A, ? extends B> mapper) { return new FailureList(left, mapper.apply(value)); } public <B> Validation<List<L>, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { Validation<?, ? extends B> result = mapper.apply(value); return (Validation<List<L>, B>)(result.isSuccess() ? new FailureList(left, result.value) : new FailureList<L, B>(new ArrayList<L>(left) {{ add(((Failure<L, B>)result).left); }}, result.value)); } }
  • 48. Monadic Validation Validation<List<String>, Person> validatedPerson = success(person).failList() .flatMap(Validator::validAge) .flatMap(Validator::validName);
  • 49. Homework: develop your own Transaction Monad The Transaction monad makes transactionally explicit in the type system, while hiding the boilerplate propagation of invoking rollbacks
  • 50. Alternative Monads Definitions Monads are parametric types with two operations flatMap and unit that obey some algebraic laws Monads are structures that represent computations defined as sequences of steps Monads are chainable containers types that confine values defining how to transform and combine them Monads are return types that guide you through the happy path
  • 51. Functional Domain Design A practical example
  • 52. A OOP BankAccount ... public class Balance { final BigDecimal amount; public Balance( BigDecimal amount ) { this.amount = amount; } } public class Account { private final String owner; private final String number; private Balance balance = new Balance(BigDecimal.ZERO); public Account( String owner, String number ) { this.owner = owner; this.number = number; } public void credit(BigDecimal value) { balance = new Balance( balance.amount.add( value ) ); } public void debit(BigDecimal value) throws InsufficientBalanceException { if (balance.amount.compareTo( value ) < 0) throw new InsufficientBalanceException(); balance = new Balance( balance.amount.subtract( value ) ); } } Mutability Error handling using Exception
  • 53. … and how we can use it Account a = new Account("Alice", "123"); Account b = new Account("Bob", "456"); Account c = new Account("Charlie", "789"); List<Account> unpaid = new ArrayList<>(); for (Account account : Arrays.asList(a, b, c)) { try { account.debit( new BigDecimal( 100.00 ) ); } catch (InsufficientBalanceException e) { unpaid.add(account); } } List<Account> unpaid = new ArrayList<>(); Stream.of(a, b, c).forEach( account -> { try { account.debit( new BigDecimal( 100.00 ) ); } catch (InsufficientBalanceException e) { unpaid.add(account); } } ); Mutation of enclosing scope Cannot use a parallel Stream Ugly syntax
  • 54. Error handling with Try monad public interface Try<A> { <B> Try<B> map(Function<A, B> f); <B> Try<B> flatMap(Function<A, Try<B>> f); boolean isFailure(); } public Success<A> implements Try<A> { private final A value; public Success(A value) { this.value = value; } public boolean isFailure() { return false; } public <B> Try<B> map(Function<A, B> f) { return new Success<>(f.apply(value)); } public <B> Try<B> flatMap(Function<A, Try<B>> f) { return f.apply(value); } } public Failure<A> implements Try<T> { private final Object error; public Failure(Object error) { this.error = error; } public boolean isFailure() { return false; } public <B> Try<B> map(Function<A, B> f) { return (Failure<B>)this; } public <B> Try<B> flatMap(Function<A, Try<B>> f) { return (Failure<B>)this; } }
  • 55. A functional BankAccount ... public class Account { private final String owner; private final String number; private final Balance balance; public Account( String owner, String number, Balance balance ) { this.owner = owner; this.number = number; this.balance = balance; } public Account credit(BigDecimal value) { return new Account( owner, number, new Balance( balance.amount.add( value ) ) ); } public Try<Account> debit(BigDecimal value) { if (balance.amount.compareTo( value ) < 0) return new Failure<>( new InsufficientBalanceError() ); return new Success<>( new Account( owner, number, new Balance( balance.amount.subtract( value ) ) ) ); } } Immutable Error handling without Exceptions
  • 56. … and how we can use it Account a = new Account("Alice", "123"); Account b = new Account("Bob", "456"); Account c = new Account("Charlie", "789"); List<Account> unpaid = Stream.of( a, b, c ) .map( account -> new Tuple2<>( account, account.debit( new BigDecimal( 100.00 ) ) ) ) .filter( t -> t._2.isFailure() ) .map( t -> t._1 ) .collect( toList() ); List<Account> unpaid = Stream.of( a, b, c ) .filter( account -> account.debit( new BigDecimal( 100.00 ) ) .isFailure() ) .collect( toList() );
  • 57. From Methods to Functions public class BankService { public static Try<Account> open(String owner, String number, BigDecimal balance) { if (initialBalance.compareTo( BigDecimal.ZERO ) < 0) return new Failure<>( new InsufficientBalanceError() ); return new Success<>( new Account( owner, number, new Balance( balance ) ) ); } public static Account credit(Account account, BigDecimal value) { return new Account( account.owner, account.number, new Balance( account.balance.amount.add( value ) ) ); } public static Try<Account> debit(Account account, BigDecimal value) { if (account.balance.amount.compareTo( value ) < 0) return new Failure<>( new InsufficientBalanceError() ); return new Success<>( new Account( account.owner, account.number, new Balance( account.balance.amount.subtract( value ) ) ) ); } }
  • 58. Decoupling state and behavior import static BankService.* Try<Account> account = open( "Alice", "123", new BigDecimal( 100.00 ) ) .map( acc -> credit( acc, new BigDecimal( 200.00 ) ) ) .map( acc -> credit( acc, new BigDecimal( 300.00 ) ) ) .flatMap( acc -> debit( acc, new BigDecimal( 400.00 ) ) ); The object-oriented paradigm couples state and behavior Functional programming decouples them
  • 59. … but I need a BankConnection! What about dependency injection?
  • 60. A naïve solution public class BankService { public static Try<Account> open(String owner, String number, BigDecimal balance, BankConnection bankConnection) { ... } public static Account credit(Account account, BigDecimal value, BankConnection bankConnection) { ... } public static Try<Account> debit(Account account, BigDecimal value, BankConnection bankConnection) { ... } } BankConnection bconn = new BankConnection(); Try<Account> account = open( "Alice", "123", new BigDecimal( 100.00 ), bconn ) .map( acc -> credit( acc, new BigDecimal( 200.00 ), bconn ) ) .map( acc -> credit( acc, new BigDecimal( 300.00 ), bconn ) ) .flatMap( acc -> debit( acc, new BigDecimal( 400.00 ), bconn ) ); Necessary to create the BankConnection in advance ... … and pass it to all methods
  • 61. Making it lazy public class BankService { public static Function<BankConnection, Try<Account>> open(String owner, String number, BigDecimal balance) { return (BankConnection bankConnection) -> ... } public static Function<BankConnection, Account> credit(Account account, BigDecimal value) { return (BankConnection bankConnection) -> ... } public static Function<BankConnection, Try<Account>> debit(Account account, BigDecimal value) { return (BankConnection bankConnection) -> ... } } Function<BankConnection, Try<Account>> f = (BankConnection conn) -> open( "Alice", "123", new BigDecimal( 100.00 ) ) .apply( conn ) .map( acc -> credit( acc, new BigDecimal( 200.00 ) ).apply( conn ) ) .map( acc -> credit( acc, new BigDecimal( 300.00 ) ).apply( conn ) ) .flatMap( acc -> debit( acc, new BigDecimal( 400.00 ) ).apply( conn ) ); Try<Account> account = f.apply( new BankConnection() );
  • 62. open Ctx -> S1 S1 A, B credit Ctx S2 C, D result open S1 A, B, Ctx injection credit C, D, Ctx, S1 resultS2 Pure OOP implementation Static Methods open A, B apply(Ctx) S1 Ctx -> S2 apply(Ctx) S2 C, D Lazy evaluation Ctx credit result
  • 63. Introducing the Reader monad ... public class Reader<R, A> { private final Function<R, A> run; public Reader( Function<R, A> run ) { this.run = run; } public <B> Reader<R, B> map(Function<A, B> f) { ... } public <B> Reader<R, B> flatMap(Function<A, Reader<R, B>> f) { ... } public A apply(R r) { return run.apply( r ); } } The reader monad provides an environment to wrap an abstract computation without evaluating it
  • 64. Introducing the Reader monad ... public class Reader<R, A> { private final Function<R, A> run; public Reader( Function<R, A> run ) { this.run = run; } public <B> Reader<R, B> map(Function<A, B> f) { return new Reader<>((R r) -> f.apply( apply( r ) )); } public <B> Reader<R, B> flatMap(Function<A, Reader<R, B>> f) { return new Reader<>((R r) -> f.apply( apply( r ) ).apply( r )); } public A apply(R r) { return run.apply( r ); } } The reader monad provides an environment to wrap an abstract computation without evaluating it
  • 65. The Reader Monad The Reader monad makes a lazy computation explicit in the type system, while hiding the logic to apply it In other words the reader monad allows us to treat functions as values with a context We can act as if we already know what the functions will return.
  • 66. … and combining it with Try public class TryReader<R, A> { private final Function<R, Try<A>> run; public TryReader( Function<R, Try<A>> run ) { this.run = run; } public <B> TryReader<R, B> map(Function<A, B> f) { ... } public <B> TryReader<R, B> mapReader(Function<A, Reader<R, B>> f) { ... } public <B> TryReader<R, B> flatMap(Function<A, TryReader<R, B>> f) { ... } public Try<A> apply(R r) { return run.apply( r ); } }
  • 67. … and combining it with Try public class TryReader<R, A> { private final Function<R, Try<A>> run; public TryReader( Function<R, Try<A>> run ) { this.run = run; } public <B> TryReader<R, B> map(Function<A, B> f) { return new TryReader<R, B>((R r) -> apply( r ) .map( a -> f.apply( a ) )); } public <B> TryReader<R, B> mapReader(Function<A, Reader<R, B>> f) { return new TryReader<R, B>((R r) -> apply( r ) .map( a -> f.apply( a ).apply( r ) )); } public <B> TryReader<R, B> flatMap(Function<A, TryReader<R, B>> f) { return new TryReader<R, B>((R r) -> apply( r ) .flatMap( a -> f.apply( a ).apply( r ) )); } public Try<A> apply(R r) { return run.apply( r ); } }
  • 68. A more user-friendly API public class BankService { public static TryReader<BankConnection, Account> open(String owner, String number, BigDecimal balance) { return new TryReader<>( (BankConnection bankConnection) -> ... ) } public static Reader<BankConnection, Account> credit(Account account, BigDecimal value) { return new Reader<>( (BankConnection bankConnection) -> ... ) } public static TryReader<BankConnection, Account> debit(Account account, BigDecimal value) { return new TryReader<>( (BankConnection bankConnection) -> ... ) } } TryReader<BankConnection, Account> reader = open( "Alice", "123", new BigDecimal( 100.00 ) ) .mapReader( acc -> credit( acc, new BigDecimal( 200.00 ) ) ) .mapReader( acc -> credit( acc, new BigDecimal( 300.00 ) ) ) .flatMap( acc -> debit( acc, new BigDecimal( 400.00 ) ) ); Try<Account> account = reader.apply( new BankConnection() );
  • 69. open Ctx -> S1 S1 A, B credit Ctx S2 C, D result open S1 A, B, Ctx injection credit C, D, Ctx, S1 resultS2 Pure OOP implementation Static Methods open A, B apply(Ctx) S1 Ctx -> S2 apply(Ctx) S2 C, D Lazy evaluation Ctx credit Reader monad result Ctx -> S1 A, B C, D map(credit) Ctx -> result apply(Ctx) open Ctx -> S2
  • 70. To recap: a Monad is a design patternAlias  flatMap that shit Intent  Put a value in a computational context defining the policy on how to operate on it Motivations  Reduce code duplication  Improve maintainability  Increase readability  Remove side effects  Hide complexity  Encapusalate implementation details  Allow composability Known Uses  Optional, Stream, Promise, Validation, Transaction, State, …
  • 71. Use Monads whenever possible to keep your code clean and encapsulate repetitive logic TL;DR
  • 73. Mario Fusco Red Hat – Senior Software Engineer mario.fusco@gmail.com twitter: @mariofusco Q A Thanks … Questions?