SlideShare a Scribd company logo
1 of 66
Download to read offline
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
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
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
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
Why mutable ?
• memory expensive!
• can't afford to keep past state in it
• re-use, overwrite, optimize
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 ?
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
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?

More Related Content

What's hot

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
 

What's hot (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
 

Viewers also liked

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
 

Viewers also liked (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)
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming languageSmritiSharma901052
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSsandhya757531
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmDeepika Walanjkar
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Sumanth A
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Coursebim.edu.pl
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Communityprachaibot
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdfAkritiPradhan2
 
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书rnrncn29
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 

Recently uploaded (20)

Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming language
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdf
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithmComputer Graphics Introduction, Open GL, Line and Circle drawing algorithm
Computer Graphics Introduction, Open GL, Line and Circle drawing algorithm
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
Katarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School CourseKatarzyna Lipka-Sidor - BIM School Course
Katarzyna Lipka-Sidor - BIM School Course
 
Prach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism CommunityPrach: A Feature-Rich Platform Empowering the Autism Community
Prach: A Feature-Rich Platform Empowering the Autism Community
 
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdfDEVICE DRIVERS AND INTERRUPTS  SERVICE MECHANISM.pdf
DEVICE DRIVERS AND INTERRUPTS SERVICE MECHANISM.pdf
 
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
『澳洲文凭』买麦考瑞大学毕业证书成绩单办理澳洲Macquarie文凭学位证书
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 

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

  • 1.
  • 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
  • 8.
  • 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
  • 11.
  • 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
  • 14.
  • 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
  • 19.
  • 20. Why mutable ? • memory expensive! • can't afford to keep past state in it • re-use, overwrite, optimize
  • 21.
  • 22.
  • 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.") } }
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 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
  • 60.
  • 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?