SlideShare ist ein Scribd-Unternehmen logo
1 von 66
Downloaden Sie, um offline zu lesen
3 things you must know to think reactive - Geecon Kraków 2015
Agenda
1. Reactive?
2. Mutability & Immutability
3. Functions & Higher-order functions
4. Why functions?
5. Functional for Reactive
Who is speaking?
• freelance software consultant based
in Vienna
• Vienna Scala User Group
• web, web, web
Who is speaking?
• freelance software consultant based in
Vienna
• Vienna Scala User Group
• web, web, web
• writing a book on reactive web-
applications
http://www.manning.com/
bernhardt
dotd051315au 50% discount
Did you say reactive?
Disambiguation
• Reactive Programming
• Functional Reactive Programming
• Reactive Application
• Responsive Web-Application
Disambiguation
• Reactive Programming async data flows
• Functional Reactive Programming async data flows + FP
• Reactive Application architectural pattern
• Responsive Web-Application Twitter Bootstrap
3 things you must know to think reactive - Geecon Kraków 2015
Why Reactive:
many cores
• End of the single-core multi-core era
• Many players in the space
• Tilera, Cavium
• Adapteva Parallela
• Xeon PHI
Why Reactive:
many cores
• Meizu MX4 Ubuntu Edition
• Octa-core MediaTek MT6595
chipset
• 2GB RAM / 20.7 MP rear camera,
2MP front-facing / 16GB built-in
flash storage
3 things you must know to think reactive - Geecon Kraków 2015
Why reactive:
distribution
(theory)
• scaling out to handle large loads
• scaling out / replication to handle
node failure
Why reactive:
distribution
(reality)
• networks, networks, networks
• they fail all the time
• Jepsen series1
1
http://aphyr.com
3 things you must know to think reactive - Geecon Kraków 2015
Reactive: how?
public class PaymentController {
public PaymentConfirmation makePayment(CreditCard card) { ... }
public PaymentHistory getPastPayments() { ... }
}
Reactive: how?
@Elastic(minNodes = 5, maxNodes = 15)
@Resilient(gracefullyHandleNetworkPartitions = true)
public class PaymentController {
@Responsive(latency = 500, timeUnit = TimeUnit.MILLISECONDS)
@MessageDriven(messageProvider = Provider.AKKA)
public PaymentConfirmation makePayment(CreditCard card) { ... }
@Responsive(latency = 800, timeUnit = TimeUnit.MILLISECONDS)
public PaymentHistory getPastPayments() { ... }
}
Why Reactive: summary
• distribution accross CPU cores
• distribution accross networked machines
• need tooling to work with this type of distribution
Mutable state
3 things you must know to think reactive - Geecon Kraków 2015
Why mutable ?
• memory expensive!
• can't afford to keep past state in it
• re-use, overwrite, optimize
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
Mutable issues - example 1
Mutable issues - example 1
$scope.reservation = {
id: 42,
start: moment({ hour: 13, minute: 15 }),
end: moment({ hour: 14, minute: 30 })
};
timeline.setOptions({
min: $scope.reservation.start.startOf('hour').toDate(),
max: $scope.reservation.start.add(3, 'hour').toDate()
});
Mutable issues - example 1
$scope.reservation = {
id: 42,
start: moment({ hour: 13, minute: 15 }),
end: moment({ hour: 14, minute: 30 })
};
timeline.setOptions({
min: $scope.reservation.start.clone().startOf('hour').toDate(),
max: $scope.reservation.start.clone().add(3, 'hour').toDate()
});
Mutable issues - example 2
car.setPosition(0);
car.setPosition(10);
Mutable issues - example 2
The problem with
locks / latches
• solution workaround for a broken
conceptual model
• huge coordination overhead! Even
more so when distributed
• hard to reason about
• performance hit
Mutability: summary
• increased difficulty for the programmer (moving parts)
• makes life hard when working concurrently
Immutable
state
Immutable state -
why now?
• main memory is cheap!
• disk memory is cheap!
We can afford copies of past state
around in order to reduce
coordination efforts
Immutable state -
how?
case class Car(brand: String, position: Int)
val car = Car(brand = "DeLorean", position = 0)
val movedCar = car.copy(position = 10)
val movedCarLaterOn = car.copy(position = 30)
Working with different
version
"Snapshots" of reality
Immutable state -
how?
• clever immutable data structures,
e.g. Bitmapped Vector Trie 2
• do not copy data around - point to
unchanged data instead
• constant time for all operations
2
http://lampwww.epfl.ch/papers/idealhashtrees.pdf
Immutable all the
way down
• immutability changes everything 3
• programming languages
• databases: insert-only, event
stores
• SSD drives
3
http://www.cidrdb.org/cidr2015/Papers/CIDR15_Paper16.pdf
Immutability: summary
• we can afford to keep everything, with good performance
• reduces the headeache of coordination accross CPU cores
and networked nodes
• audit trail of changes for free
Functions
Functions, the Starwars Lego way
(three kinds of awesome united)
Pure function
Side-effecting function
Side-effecting function
Side-effecting function
The dark side clouds everything. Impossible to see the future is.
-- Master Yoda
Again a pure function
(this time with a laser gun)
Hmm...
Function composition
Function composition
def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ...
def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ...
Function composition
def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ...
def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ...
def build(parts: (Head, Body, Legs, Hair), lg: LaserGun):
ArmedHanSolo =
arm(assemble(parts), lg)
Higher-order
functions
Definition
A function that takes
another function as
parameter (or produces a
function as result).
Higher-order
functions
val users: List[User] = ...
val (minors, majors) =
users.partition(_.age < 18)
Higher-order
functions
val users: List[User] = ...
val isMinor =
(user: User) => user.age < 18
val (minors, majors) =
users.partition(isMinor)
Higher-order functions
def AuthenticatedAction(f: Request => User => Result) = Action { request =>
findUser(request).map { user =>
f(request)(user)
} getOrElse {
Unauthorized("Get out!")
}
}
def showSettings = AuthenticatedAction { request =>
user =>
userSettingsService.findSettings(user).map { settings =>
Ok(views.html.settings(user, settings))
} getOrElse {
NotFound("We lost all your settings. Sorry.")
}
}
Functions - Why ?
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
Functions
• portable and re-usable behaviour
• data changes, behaviour can be re-
used
• functions as data transformation
pipelines
Functions = data transformation
pipelines
val addresses = users.filter(_.age > 18)
.map(_.address)
.sortBy(_.city)
Build increasingly complex behaviour through a series
of transformations driven by composing functions
3 things you must know to think reactive - Geecon Kraków 2015
Functional
for reactive
Reactive
applications
• distributed in nature
• need to be resilient to failure, adapt
to changes
• asynchronous all the way down
Asynchronous
callback hell
var fetchPriceList = function() {
$.get('/items', function(items) {
var priceList = [];
items.forEach(function(item, itemIndex) {
$.get('/prices', { itemId: item.id }, function(price) {
priceList.push({ item: item, price: price });
if ( priceList.length == items.length ) {
return priceList;
}
}).fail(function() {
priceList.push({ item: item });
if ( priceList.length == items.length ) {
return priceList;
}
});
}
}).fail(function() {
alert("Could not retrieve items");
});
}
Asynchronous &
functional
val fetchItems = WS.get("/items").getJSON[List[Item]]()
val fetchPrices = WS.get("/prices").getJSON[List[Price]]()
val itemPrices: Future[List[(Item, Option[Price])]] = for {
items <- fetchItems
prices <- fetchPrices
} yield {
item -> items.flatMap { item =>
prices.find(_.itemId == item.id)
}
}
itemPrices.recover {
case ce: ConnectionException =>
log.error("Could not retrieve items")
List.empty
}
Immutable
Function
Composition
Thank you
http://www.manning.com/bernhardt
code dotd051315au 50% discount
@elmanu / manuel@bernhardt.io
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupkrivachy
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka featuresGrzegorz Duda
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsKonrad Malawski
 
Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Clustermiciek
 
The internet of (lego) trains
The internet of (lego) trainsThe internet of (lego) trains
The internet of (lego) trainsGrzegorz Duda
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupRoy Russo
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConfJohan Andrén
 
State of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeKonrad Malawski
 
Async – react, don't wait
Async – react, don't waitAsync – react, don't wait
Async – react, don't waitJohan Andrén
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesKonrad Malawski
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Johan Andrén
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)Konrad Malawski
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 

Was ist angesagt? (20)

The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetup
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
 
Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Cluster
 
The internet of (lego) trains
The internet of (lego) trainsThe internet of (lego) trains
The internet of (lego) trains
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConf
 
State of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to come
 
Async – react, don't wait
Async – react, don't waitAsync – react, don't wait
Async – react, don't wait
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutes
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Building reactive distributed systems with Akka
Building reactive distributed systems with Akka
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 

Andere mochten auch

Game-based learning
Game-based learningGame-based learning
Game-based learningeandreeva
 
EAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint PresentationEAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint PresentationJose Vazquez
 
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...Tanil Ozkan
 
Eagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-DesignEagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-DesignJuliane Tran Cong
 
Career Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary AgesCareer Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary AgesMichael Fork
 
Gaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen könnenGaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen könnenSebastian Deterding
 
Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE Premier Farnell
 
Best Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTIBest Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTIChristine Shine
 
The eagle power point
The eagle power pointThe eagle power point
The eagle power pointYonit Weil
 
Wolf presentation
Wolf presentationWolf presentation
Wolf presentationXalus
 
MBTI Type Presentation--Introduction
MBTI Type Presentation--IntroductionMBTI Type Presentation--Introduction
MBTI Type Presentation--IntroductionStaci A. Inskeep
 
New electronics slides
New electronics slidesNew electronics slides
New electronics slidesjogajosh
 
12 Changes To Make You Happier at Work
12 Changes To Make You Happier at Work12 Changes To Make You Happier at Work
12 Changes To Make You Happier at WorkWhen I Work
 
Meme Powerpoint
Meme PowerpointMeme Powerpoint
Meme PowerpointConnor
 
Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)yeokm1
 

Andere mochten auch (20)

When Dev met Ops
When Dev met OpsWhen Dev met Ops
When Dev met Ops
 
Game-based learning
Game-based learningGame-based learning
Game-based learning
 
EAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint PresentationEAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint Presentation
 
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
 
Eagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-DesignEagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-Design
 
Mbti for everybody ii
Mbti for everybody   iiMbti for everybody   ii
Mbti for everybody ii
 
Power supply
Power supplyPower supply
Power supply
 
Coca cola
Coca colaCoca cola
Coca cola
 
Mbti
MbtiMbti
Mbti
 
Career Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary AgesCareer Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary Ages
 
Gaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen könnenGaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen können
 
Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE
 
Best Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTIBest Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTI
 
The eagle power point
The eagle power pointThe eagle power point
The eagle power point
 
Wolf presentation
Wolf presentationWolf presentation
Wolf presentation
 
MBTI Type Presentation--Introduction
MBTI Type Presentation--IntroductionMBTI Type Presentation--Introduction
MBTI Type Presentation--Introduction
 
New electronics slides
New electronics slidesNew electronics slides
New electronics slides
 
12 Changes To Make You Happier at Work
12 Changes To Make You Happier at Work12 Changes To Make You Happier at Work
12 Changes To Make You Happier at Work
 
Meme Powerpoint
Meme PowerpointMeme Powerpoint
Meme Powerpoint
 
Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)
 

Ähnlich wie 3 things you must know to think reactive - Geecon Kraków 2015

Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMManuel Bernhardt
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTPMustafa TURAN
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaHermann Hueck
 
What's Coming Next in Sencha Frameworks
What's Coming Next in Sencha FrameworksWhat's Coming Next in Sencha Frameworks
What's Coming Next in Sencha FrameworksGrgur Grisogono
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
From polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratchFrom polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratchSergi González Pérez
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)Igalia
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaYardena Meymann
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Event Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingEvent Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingGlobalLogic Ukraine
 

Ähnlich wie 3 things you must know to think reactive - Geecon Kraków 2015 (20)

Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
What's Coming Next in Sencha Frameworks
What's Coming Next in Sencha FrameworksWhat's Coming Next in Sencha Frameworks
What's Coming Next in Sencha Frameworks
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
huhu
huhuhuhu
huhu
 
From polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratchFrom polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratch
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Event Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingEvent Sourcing and Functional Programming
Event Sourcing and Functional Programming
 

Mehr von Manuel Bernhardt

Is there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems HamburgIs there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems HamburgManuel Bernhardt
 
Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018Manuel Bernhardt
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?Manuel Bernhardt
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?Manuel Bernhardt
 
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 20178 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017Manuel Bernhardt
 
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware ofScala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware ofManuel Bernhardt
 
8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware of8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware ofManuel Bernhardt
 
Beyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practiceBeyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practiceManuel Bernhardt
 
Beyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practiceBeyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practiceManuel Bernhardt
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and countingManuel Bernhardt
 
Project Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 monthsProject Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 monthsManuel Bernhardt
 
Tips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 projectTips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 projectManuel Bernhardt
 

Mehr von Manuel Bernhardt (16)

Is there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems HamburgIs there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems Hamburg
 
Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?
 
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 20178 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
 
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware ofScala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
 
8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware of8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware of
 
Beyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practiceBeyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practice
 
Beyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practiceBeyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practice
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and counting
 
Writing a technical book
Writing a technical bookWriting a technical book
Writing a technical book
 
Project Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 monthsProject Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 months
 
Scala - Java2Days Sofia
Scala - Java2Days SofiaScala - Java2Days Sofia
Scala - Java2Days Sofia
 
Tips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 projectTips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 project
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala pitfalls
Scala pitfallsScala pitfalls
Scala pitfalls
 

Kürzlich hochgeladen

GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS Bahzad5
 
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfJulia Kaye
 
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Apollo Techno Industries Pvt Ltd
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Akarthi keyan
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesDIPIKA83
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxLMW Machine Tool Division
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Sean Meyn
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchrohitcse52
 
Landsman converter for power factor improvement
Landsman converter for power factor improvementLandsman converter for power factor improvement
Landsman converter for power factor improvementVijayMuni2
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingMarian Marinov
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide LaboratoryBahzad5
 
How to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdfHow to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdfRedhwan Qasem Shaddad
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecTrupti Shiralkar, CISSP
 
EPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptxEPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptxJoseeMusabyimana
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxHome
 
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxIT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxSAJITHABANUS
 

Kürzlich hochgeladen (20)

GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
 
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
 
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part A
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display Devices
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
 
Présentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdfPrésentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdf
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
 
Landsman converter for power factor improvement
Landsman converter for power factor improvementLandsman converter for power factor improvement
Landsman converter for power factor improvement
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & Logging
 
Lecture 2 .pdf
Lecture 2                           .pdfLecture 2                           .pdf
Lecture 2 .pdf
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
 
Présentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdfPrésentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdf
 
How to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdfHow to Write a Good Scientific Paper.pdf
How to Write a Good Scientific Paper.pdf
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
 
EPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptxEPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptx
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptx
 
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxIT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
 
計劃趕得上變化
計劃趕得上變化計劃趕得上變化
計劃趕得上變化
 

3 things you must know to think reactive - Geecon Kraków 2015

  • 2. Agenda 1. Reactive? 2. Mutability & Immutability 3. Functions & Higher-order functions 4. Why functions? 5. Functional for Reactive
  • 3. Who is speaking? • freelance software consultant based in Vienna • Vienna Scala User Group • web, web, web
  • 4. Who is speaking? • freelance software consultant based in Vienna • Vienna Scala User Group • web, web, web • writing a book on reactive web- applications http://www.manning.com/ bernhardt dotd051315au 50% discount
  • 5. Did you say reactive?
  • 6. Disambiguation • Reactive Programming • Functional Reactive Programming • Reactive Application • Responsive Web-Application
  • 7. Disambiguation • Reactive Programming async data flows • Functional Reactive Programming async data flows + FP • Reactive Application architectural pattern • Responsive Web-Application Twitter Bootstrap
  • 9. Why Reactive: many cores • End of the single-core multi-core era • Many players in the space • Tilera, Cavium • Adapteva Parallela • Xeon PHI
  • 10. Why Reactive: many cores • Meizu MX4 Ubuntu Edition • Octa-core MediaTek MT6595 chipset • 2GB RAM / 20.7 MP rear camera, 2MP front-facing / 16GB built-in flash storage
  • 12. Why reactive: distribution (theory) • scaling out to handle large loads • scaling out / replication to handle node failure
  • 13. Why reactive: distribution (reality) • networks, networks, networks • they fail all the time • Jepsen series1 1 http://aphyr.com
  • 15. Reactive: how? public class PaymentController { public PaymentConfirmation makePayment(CreditCard card) { ... } public PaymentHistory getPastPayments() { ... } }
  • 16. Reactive: how? @Elastic(minNodes = 5, maxNodes = 15) @Resilient(gracefullyHandleNetworkPartitions = true) public class PaymentController { @Responsive(latency = 500, timeUnit = TimeUnit.MILLISECONDS) @MessageDriven(messageProvider = Provider.AKKA) public PaymentConfirmation makePayment(CreditCard card) { ... } @Responsive(latency = 800, timeUnit = TimeUnit.MILLISECONDS) public PaymentHistory getPastPayments() { ... } }
  • 17. Why Reactive: summary • distribution accross CPU cores • distribution accross networked machines • need tooling to work with this type of distribution
  • 20. Why mutable ? • memory expensive! • can't afford to keep past state in it • re-use, overwrite, optimize
  • 23. Mutable issues - example 1
  • 24. Mutable issues - example 1 $scope.reservation = { id: 42, start: moment({ hour: 13, minute: 15 }), end: moment({ hour: 14, minute: 30 }) }; timeline.setOptions({ min: $scope.reservation.start.startOf('hour').toDate(), max: $scope.reservation.start.add(3, 'hour').toDate() });
  • 25. Mutable issues - example 1 $scope.reservation = { id: 42, start: moment({ hour: 13, minute: 15 }), end: moment({ hour: 14, minute: 30 }) }; timeline.setOptions({ min: $scope.reservation.start.clone().startOf('hour').toDate(), max: $scope.reservation.start.clone().add(3, 'hour').toDate() });
  • 26. Mutable issues - example 2 car.setPosition(0); car.setPosition(10);
  • 27. Mutable issues - example 2
  • 28. The problem with locks / latches • solution workaround for a broken conceptual model • huge coordination overhead! Even more so when distributed • hard to reason about • performance hit
  • 29. Mutability: summary • increased difficulty for the programmer (moving parts) • makes life hard when working concurrently
  • 31. Immutable state - why now? • main memory is cheap! • disk memory is cheap! We can afford copies of past state around in order to reduce coordination efforts
  • 32. Immutable state - how? case class Car(brand: String, position: Int) val car = Car(brand = "DeLorean", position = 0) val movedCar = car.copy(position = 10) val movedCarLaterOn = car.copy(position = 30) Working with different version "Snapshots" of reality
  • 33. Immutable state - how? • clever immutable data structures, e.g. Bitmapped Vector Trie 2 • do not copy data around - point to unchanged data instead • constant time for all operations 2 http://lampwww.epfl.ch/papers/idealhashtrees.pdf
  • 34. Immutable all the way down • immutability changes everything 3 • programming languages • databases: insert-only, event stores • SSD drives 3 http://www.cidrdb.org/cidr2015/Papers/CIDR15_Paper16.pdf
  • 35. Immutability: summary • we can afford to keep everything, with good performance • reduces the headeache of coordination accross CPU cores and networked nodes • audit trail of changes for free
  • 37. Functions, the Starwars Lego way (three kinds of awesome united)
  • 41. Side-effecting function The dark side clouds everything. Impossible to see the future is. -- Master Yoda
  • 42. Again a pure function (this time with a laser gun)
  • 45. Function composition def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ... def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ...
  • 46. Function composition def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ... def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ... def build(parts: (Head, Body, Legs, Hair), lg: LaserGun): ArmedHanSolo = arm(assemble(parts), lg)
  • 48. Definition A function that takes another function as parameter (or produces a function as result).
  • 49. Higher-order functions val users: List[User] = ... val (minors, majors) = users.partition(_.age < 18)
  • 50. Higher-order functions val users: List[User] = ... val isMinor = (user: User) => user.age < 18 val (minors, majors) = users.partition(isMinor)
  • 51. Higher-order functions def AuthenticatedAction(f: Request => User => Result) = Action { request => findUser(request).map { user => f(request)(user) } getOrElse { Unauthorized("Get out!") } } def showSettings = AuthenticatedAction { request => user => userSettingsService.findSettings(user).map { settings => Ok(views.html.settings(user, settings)) } getOrElse { NotFound("We lost all your settings. Sorry.") } }
  • 58. Functions • portable and re-usable behaviour • data changes, behaviour can be re- used • functions as data transformation pipelines
  • 59. Functions = data transformation pipelines val addresses = users.filter(_.age > 18) .map(_.address) .sortBy(_.city) Build increasingly complex behaviour through a series of transformations driven by composing functions
  • 62. Reactive applications • distributed in nature • need to be resilient to failure, adapt to changes • asynchronous all the way down
  • 63. Asynchronous callback hell var fetchPriceList = function() { $.get('/items', function(items) { var priceList = []; items.forEach(function(item, itemIndex) { $.get('/prices', { itemId: item.id }, function(price) { priceList.push({ item: item, price: price }); if ( priceList.length == items.length ) { return priceList; } }).fail(function() { priceList.push({ item: item }); if ( priceList.length == items.length ) { return priceList; } }); } }).fail(function() { alert("Could not retrieve items"); }); }
  • 64. Asynchronous & functional val fetchItems = WS.get("/items").getJSON[List[Item]]() val fetchPrices = WS.get("/prices").getJSON[List[Price]]() val itemPrices: Future[List[(Item, Option[Price])]] = for { items <- fetchItems prices <- fetchPrices } yield { item -> items.flatMap { item => prices.find(_.itemId == item.id) } } itemPrices.recover { case ce: ConnectionException => log.error("Could not retrieve items") List.empty }
  • 66. Thank you http://www.manning.com/bernhardt code dotd051315au 50% discount @elmanu / manuel@bernhardt.io Questions?