SlideShare une entreprise Scribd logo
1  sur  82
Closures
                   The Next “Big Thing” in Java

                                    Russel Winder
                                  email: russel@winder.org.uk
                                 xmpp: russel@winder.org.uk
                                    twitter: @russel_winder




Copyright © 2012 Russel Winder                                  1
Closures
                 The Next “Big Thing” in Java?

                                    Russel Winder
                                  email: russel@winder.org.uk
                                 xmpp: russel@winder.org.uk
                                    twitter: @russel_winder




Copyright © 2012 Russel Winder                                  2
Aims, Goals and Objectives
     ●   Investigate why some idioms from Java 0–7 lead to
         bad code in a post-Java 7 world.
     ●   Show what some of the idioms of Java 8 and beyond
         are likely to be.
     ●   Survive to the end of the session.




Copyright © 2012 Russel Winder                               3
Structure


                                 A beginning.

                                  A middle.

                                   An end.

Copyright © 2012 Russel Winder                  4
Interstitial Advertisement




Copyright © 2012 Russel Winder                        5
A Beginning




Copyright © 2012 Russel Winder                 6
Many people are still using Java 1.4.




Copyright © 2012 Russel Winder                         7
They see no reason to move to any
                            later version of Java:
                     no real benefit, for too much pain.




Copyright © 2012 Russel Winder                             8
Java 5 is a barrier too far for them.




Copyright © 2012 Russel Winder                      9
The Java 7 → Java 8 change
            is an even more disruptive change.




Copyright © 2012 Russel Winder                   10
This possibly means Java
                            is now a legacy language?




Copyright © 2012 Russel Winder                          11
No, it's an opportunity to stop
                 programming using 1970s techniques
                      and start using 1930s ones.




Copyright © 2012 Russel Winder                        12
Alonzo Church
                                   Alan Turing
                                 Stephen Kleene
                                    J B Rosser




Copyright © 2012 Russel Winder                    13
And an opportunity to do 1990s programming.




Copyright © 2012 Russel Winder                      14
i.e. We finally get to do real object-oriented
                    programming using Java.




Copyright © 2012 Russel Winder                             15
Another Beginning




Copyright © 2012 Russel Winder                       16
What is a “closure”?




Copyright © 2012 Russel Winder                          17
A closure is a function with an associated
        environment containing values for all the free
                  variables in the function.




Copyright © 2012 Russel Winder                           18
A Function



                                 Integer f(final Integer x) {
                                   return x * y ;
                                 }




                                                    Free variable.



Copyright © 2012 Russel Winder                                       19
A closure should be referentially transparent.

              Whenever function f is evaluated on the same value,
                   a say, then the same value is returned.

                                   f(a) = b




Copyright © 2012 Russel Winder                                      20
Java has had things (sort of) like this
                      since (almost) the beginning…




Copyright © 2012 Russel Winder                               21
A closure can be realized as an instance of
                 a class with a single method and
                      single assignment fields.




Copyright © 2012 Russel Winder                            22
public class ClosureClass {
                               private final Integer multiplier;
                               public ClosureClass(final Integer m) {
                                  multiplier = m;
                               }
                               public Integer call(final Integer i) {
                                  return multiplier * i;
                               }
                             }


                                                No free variables in call.

Copyright © 2012 Russel Winder                                               23
final ClosureClass multiplyBy5 = new ClosureClass(5);




                                 multiplyBy5.call(4)




Copyright © 2012 Russel Winder                                  24
Alternatively…




Copyright © 2012 Russel Winder                    25
public interface ClosureInterface<T> {
      T call(T t);
    }


                        final ClosureInterface<Integer> multiplyBy5 =
                           new ClosureInterface<Integer>() {
                                 public Integer call(final Integer i) {
                                   return 5 * i;
                                 }
                              };



                                                     multiplyBy5.call(4)

Copyright © 2012 Russel Winder                                             26
If Java had operator overloading, this
                    could be made to look much nicer.




Copyright © 2012 Russel Winder                             27
Just as it can in proper programming languages
         such as Groovy, Scala, C++, Python, etc.




Copyright © 2012 Russel Winder                        28
final multiplyBy5 = {i -> 5 * i}


                                              final multiplyBy5 = {5 * it}




                                 multiplyBy5(4)




                                         multiplyBy5.call(4)


Copyright © 2012 Russel Winder                                               29
def multiplyBy5(i: Int): Int = 5 * i




                                             multiplyBy5(4)




Copyright © 2012 Russel Winder                                     30
But Java 8 can do stuff a bit like that…




Copyright © 2012 Russel Winder                             31
final ClosureInterface<Integer> multiplyBy5 = i -> 5 * i;




                                       multiplyBy5.call(4)




Copyright © 2012 Russel Winder                                           32
Nothing much revolutionary here,
                        just a bit of syntactic sugar…




Copyright © 2012 Russel Winder                           33
…true, but that isn't all there is…




Copyright © 2012 Russel Winder                             34
A Middle




Copyright © 2012 Russel Winder              35
It all about where the iteration is.




Copyright © 2012 Russel Winder                           36
Explicit iteration

                                        vs.

                                 Implicit iteration




Copyright © 2012 Russel Winder                        37
Work with a (trivial) example:




Copyright © 2012 Russel Winder                           38
Calculate the sum of the squares of the
           numbers between 0 and 100 that are
                       divisible by 7.




Copyright © 2012 Russel Winder                      39
final List<Integer> numbers = new ArrayList<>();
                            for (int i = 0; i < 100; ++i) {
                               if (i % 7 == 0) {
                                  numbers.add(i);
                               }
                            }
                            Integer sum = 0 ;
                            for (final Integer i: numbers) {
                               sum += i * i;
                            }




Copyright © 2012 Russel Winder                                                 40
(for (i <- 0 until 100; if i % 7 == 0) yield i * i).sum




Copyright © 2012 Russel Winder                                       41
sum(i * i for i in range(100) if i % 7 == 0)




Copyright © 2012 Russel Winder                                   42
(0 until 100).filter(i => i %7 == 0).map(i => i * i).sum




Copyright © 2012 Russel Winder                                     43
(0..100).findAll{i -> i % 7 == 0}.collect{i -> i * i}.sum()




Copyright © 2012 Russel Winder                                        44
(0..100).findAll{it % 7 == 0}.collect{it * it}.sum()




Copyright © 2012 Russel Winder                                     45
numbers.filter(i -> i % 7 == 0).map(i -> i * i).reduce(0, (t, x) -> t + x)




                                 Huh?


Copyright © 2012 Russel Winder                                           46
final List<Integer> numbers = new ArrayList<>();
                  for (int i = 0; i < 100; ++i) { numbers.add(i); }




                                                             Oh ffs.
Copyright © 2012 Russel Winder                                         47
Higher Order Functions




Copyright © 2012 Russel Winder                            48
Functions that take functions as parameters
         and/or return functions as result.




Copyright © 2012 Russel Winder                    49
Some may be thinking:
                                  Why do I give a f###




Copyright © 2012 Russel Winder                           50
After all nothing good has happened
                     in Java since Java 1.4.2.




Copyright © 2012 Russel Winder                       51
Copyright © 2012 Russel Winder   52
Because all computers are
                             now parallel computers.




Copyright © 2012 Russel Winder                          53
Copyright © 2012 Russel Winder   54
We have to move to an attitude where we
             assume our software is not uniprocessor.




Copyright © 2012 Russel Winder                          55
We have to actually do object-oriented and
             functional programming.




Copyright © 2012 Russel Winder                    56
Instead of just saying we write Java and so are
            doing object-oriented programming.




Copyright © 2012 Russel Winder                           57
numbers.parallel().filter(i -> i % 7 == 0).
                      map(i -> i * i).reduce(0, (t, x) -> t + x)




Copyright © 2012 Russel Winder                                     58
GParsPool.withPool {
     value = (0..100).findAllParallel{it % 7 == 0}.collectParallel{it * it}.sum()
   }




Copyright © 2012 Russel Winder                                                      59
GParsPool.withPool {
             value = (0..100).parallel.filter{it % 7 == 0}.map{it * it}.sum()
           }




                                                              Very Java 8.
Copyright © 2012 Russel Winder                                                  60
def value = (0..100)
     ParallelEnhancer.enhanceInstance(value)
     value = value.parallel.filter{it % 7 == 0}.map{it * it}.sum()




Copyright © 2012 Russel Winder                                       61
def value = (0..100)
     ParallelEnhancer.enhanceInstance(value)
     value = value.findAllParallel{it % 7 == 0}.collectParallel{it * it}.sum()




Copyright © 2012 Russel Winder                                                   62
GPars and Groovy give you Java 8 style
                   approach and parallelism today
                      for Java with JDK6 or JDK7.




Copyright © 2012 Russel Winder                            63
Guava, TotallyLazy, and FunctionalJava can be used
      today to practice the functional approach using Java.

                    Or just install the JDK8 Lambda release.




Copyright © 2012 Russel Winder                                 64
Using Scala is an option for
                       doing functional programming*.




Copyright © 2012 Russel Winder
                                    *And just ignore Java altogether.   65
(0 until 100).par.filter(i => i %7 == 0).map(i => i * i).sum




Copyright © 2012 Russel Winder                                         66
An End




Copyright © 2012 Russel Winder            67
Java is about to get the functional
                         programming aspect.




Copyright © 2012 Russel Winder                          68
Java is about to become
                        an object-oriented language.




Copyright © 2012 Russel Winder                         69
Scala, Groovy, Python, C++, etc.
         already have object-oriented and functional.




Copyright © 2012 Russel Winder                          70
It's all about how your data evolves.

                  It's not about the flow of control.




Copyright © 2012 Russel Winder                          71
It's all about sending messages to your
                  objects, requesting activity.




Copyright © 2012 Russel Winder                       72
Closure the next “big thing” in Java?




Copyright © 2012 Russel Winder                         73
Copyright © 2012 Russel Winder   74
Squirrels deny parallelism.



Copyright © 2012 Russel Winder    75
Copyright © 2012 Russel Winder   76
Yes*.



                                  *But will everyone ignore it?
Copyright © 2012 Russel Winder                                    77
No.



Copyright © 2012 Russel Winder         78
It is not the lambda expressions in Java 8 that is
                  the disruptive revolution.

              It's the change to the Java library that is.

                 It's all about those defender methods.




Copyright © 2012 Russel Winder                               79
Surreptitious Advertisement




Copyright © 2012 Russel Winder                     80
The End




Copyright © 2012 Russel Winder             81
Closures
                 The Next “Big Thing” in Java?

                                    Russel Winder
                                  email: russel@winder.org.uk
                                 xmpp: russel@winder.org.uk
                                    twitter: @russel_winder




Copyright © 2012 Russel Winder                                  82

Contenu connexe

En vedette

SolarWinds Federal Cybersecurity Survey
SolarWinds Federal Cybersecurity SurveySolarWinds Federal Cybersecurity Survey
SolarWinds Federal Cybersecurity SurveySolarWinds
 
Mise en place d'un suivi des conversions Adwords avancé avec GTM sur Wordpress
Mise en place d'un suivi des conversions Adwords avancé avec GTM sur WordpressMise en place d'un suivi des conversions Adwords avancé avec GTM sur Wordpress
Mise en place d'un suivi des conversions Adwords avancé avec GTM sur WordpressBruno Guyot
 
Heaven x Dupont Lewis : #Foodporn
Heaven x Dupont Lewis : #FoodpornHeaven x Dupont Lewis : #Foodporn
Heaven x Dupont Lewis : #FoodpornPetit Web
 
Crédit socring, l'octroi des cartes bancaires (présentation)
Crédit socring, l'octroi des cartes bancaires (présentation)Crédit socring, l'octroi des cartes bancaires (présentation)
Crédit socring, l'octroi des cartes bancaires (présentation)Marwen Allaguy
 
25 de noviembre. no a la violencia de género
25 de noviembre. no a la violencia de género25 de noviembre. no a la violencia de género
25 de noviembre. no a la violencia de géneroasoraya10
 
#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...
#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...
#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...Toshiaki Maki
 
Stratégie de contenu web marketing : un défi pour les entreprises
Stratégie de contenu web marketing : un défi pour les entreprisesStratégie de contenu web marketing : un défi pour les entreprises
Stratégie de contenu web marketing : un défi pour les entreprisesEditoile
 
несклоняемые имена существительные
несклоняемые имена существительныенесклоняемые имена существительные
несклоняемые имена существительныеNatalya Dyrda
 
Иркутск - середина Земли
Иркутск - середина ЗемлиИркутск - середина Земли
Иркутск - середина ЗемлиNatalya Dyrda
 
La stratégie du choc naomi klein
La stratégie du choc   naomi kleinLa stratégie du choc   naomi klein
La stratégie du choc naomi kleinMMenier
 
Rewards & loyalty program with Hitachi Solutions Ecommerce
Rewards & loyalty program with Hitachi Solutions EcommerceRewards & loyalty program with Hitachi Solutions Ecommerce
Rewards & loyalty program with Hitachi Solutions EcommerceHitachi Solutions America, Ltd.
 

En vedette (12)

SolarWinds Federal Cybersecurity Survey
SolarWinds Federal Cybersecurity SurveySolarWinds Federal Cybersecurity Survey
SolarWinds Federal Cybersecurity Survey
 
GWT Reloaded
GWT ReloadedGWT Reloaded
GWT Reloaded
 
Mise en place d'un suivi des conversions Adwords avancé avec GTM sur Wordpress
Mise en place d'un suivi des conversions Adwords avancé avec GTM sur WordpressMise en place d'un suivi des conversions Adwords avancé avec GTM sur Wordpress
Mise en place d'un suivi des conversions Adwords avancé avec GTM sur Wordpress
 
Heaven x Dupont Lewis : #Foodporn
Heaven x Dupont Lewis : #FoodpornHeaven x Dupont Lewis : #Foodporn
Heaven x Dupont Lewis : #Foodporn
 
Crédit socring, l'octroi des cartes bancaires (présentation)
Crédit socring, l'octroi des cartes bancaires (présentation)Crédit socring, l'octroi des cartes bancaires (présentation)
Crédit socring, l'octroi des cartes bancaires (présentation)
 
25 de noviembre. no a la violencia de género
25 de noviembre. no a la violencia de género25 de noviembre. no a la violencia de género
25 de noviembre. no a la violencia de género
 
#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...
#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...
#jjug_ccc #ccc_gh5 What's new in Spring Framework 4.3 / Boot 1.4 + Pivotal's ...
 
Stratégie de contenu web marketing : un défi pour les entreprises
Stratégie de contenu web marketing : un défi pour les entreprisesStratégie de contenu web marketing : un défi pour les entreprises
Stratégie de contenu web marketing : un défi pour les entreprises
 
несклоняемые имена существительные
несклоняемые имена существительныенесклоняемые имена существительные
несклоняемые имена существительные
 
Иркутск - середина Земли
Иркутск - середина ЗемлиИркутск - середина Земли
Иркутск - середина Земли
 
La stratégie du choc naomi klein
La stratégie du choc   naomi kleinLa stratégie du choc   naomi klein
La stratégie du choc naomi klein
 
Rewards & loyalty program with Hitachi Solutions Ecommerce
Rewards & loyalty program with Hitachi Solutions EcommerceRewards & loyalty program with Hitachi Solutions Ecommerce
Rewards & loyalty program with Hitachi Solutions Ecommerce
 

Similaire à Closures, the next "Big Thing" in Java: Russel Winder

Java 8: a New Beginning
Java 8: a New BeginningJava 8: a New Beginning
Java 8: a New BeginningRussel Winder
 
Why Groovy When Java 8 or Scala, or…
Why Groovy When Java 8 or Scala, or…Why Groovy When Java 8 or Scala, or…
Why Groovy When Java 8 or Scala, or…Russel Winder
 
Given Groovy Who Needs Java
Given Groovy Who Needs JavaGiven Groovy Who Needs Java
Given Groovy Who Needs JavaRussel Winder
 
ACCU 2012: Go, D, C++ and The Multicore Revolution
ACCU 2012:  Go, D, C++ and The Multicore RevolutionACCU 2012:  Go, D, C++ and The Multicore Revolution
ACCU 2012: Go, D, C++ and The Multicore RevolutionRussel Winder
 
Testing: Python, Java, Groovy, etc.
Testing: Python, Java, Groovy, etc.Testing: Python, Java, Groovy, etc.
Testing: Python, Java, Groovy, etc.Russel Winder
 
It's all about processes communicating - Russel Winder
It's all about processes communicating - Russel WinderIt's all about processes communicating - Russel Winder
It's all about processes communicating - Russel WinderJAX London
 
It's All About Processes Communicating
It's All About Processes CommunicatingIt's All About Processes Communicating
It's All About Processes CommunicatingRussel Winder
 
The Case for Kotlin and Ceylon
The Case for Kotlin and CeylonThe Case for Kotlin and Ceylon
The Case for Kotlin and CeylonRussel Winder
 
GroovyFX: or how to program JavaFX easily
GroovyFX: or how to program JavaFX easily GroovyFX: or how to program JavaFX easily
GroovyFX: or how to program JavaFX easily Russel Winder
 
Java is Dead, Long Live Ceylon, Kotlin, etc
Java is Dead,  Long Live Ceylon, Kotlin, etcJava is Dead,  Long Live Ceylon, Kotlin, etc
Java is Dead, Long Live Ceylon, Kotlin, etcRussel Winder
 
Java is dead, long live Scala, Kotlin, Ceylon, etc.
Java is dead, long live Scala, Kotlin, Ceylon, etc.Java is dead, long live Scala, Kotlin, Ceylon, etc.
Java is dead, long live Scala, Kotlin, Ceylon, etc.Russel Winder
 
Java is dead, long live Scala Kotlin Ceylon etc.
Java is dead, long live Scala Kotlin Ceylon etc.Java is dead, long live Scala Kotlin Ceylon etc.
Java is dead, long live Scala Kotlin Ceylon etc.Russel Winder
 

Similaire à Closures, the next "Big Thing" in Java: Russel Winder (12)

Java 8: a New Beginning
Java 8: a New BeginningJava 8: a New Beginning
Java 8: a New Beginning
 
Why Groovy When Java 8 or Scala, or…
Why Groovy When Java 8 or Scala, or…Why Groovy When Java 8 or Scala, or…
Why Groovy When Java 8 or Scala, or…
 
Given Groovy Who Needs Java
Given Groovy Who Needs JavaGiven Groovy Who Needs Java
Given Groovy Who Needs Java
 
ACCU 2012: Go, D, C++ and The Multicore Revolution
ACCU 2012:  Go, D, C++ and The Multicore RevolutionACCU 2012:  Go, D, C++ and The Multicore Revolution
ACCU 2012: Go, D, C++ and The Multicore Revolution
 
Testing: Python, Java, Groovy, etc.
Testing: Python, Java, Groovy, etc.Testing: Python, Java, Groovy, etc.
Testing: Python, Java, Groovy, etc.
 
It's all about processes communicating - Russel Winder
It's all about processes communicating - Russel WinderIt's all about processes communicating - Russel Winder
It's all about processes communicating - Russel Winder
 
It's All About Processes Communicating
It's All About Processes CommunicatingIt's All About Processes Communicating
It's All About Processes Communicating
 
The Case for Kotlin and Ceylon
The Case for Kotlin and CeylonThe Case for Kotlin and Ceylon
The Case for Kotlin and Ceylon
 
GroovyFX: or how to program JavaFX easily
GroovyFX: or how to program JavaFX easily GroovyFX: or how to program JavaFX easily
GroovyFX: or how to program JavaFX easily
 
Java is Dead, Long Live Ceylon, Kotlin, etc
Java is Dead,  Long Live Ceylon, Kotlin, etcJava is Dead,  Long Live Ceylon, Kotlin, etc
Java is Dead, Long Live Ceylon, Kotlin, etc
 
Java is dead, long live Scala, Kotlin, Ceylon, etc.
Java is dead, long live Scala, Kotlin, Ceylon, etc.Java is dead, long live Scala, Kotlin, Ceylon, etc.
Java is dead, long live Scala, Kotlin, Ceylon, etc.
 
Java is dead, long live Scala Kotlin Ceylon etc.
Java is dead, long live Scala Kotlin Ceylon etc.Java is dead, long live Scala Kotlin Ceylon etc.
Java is dead, long live Scala Kotlin Ceylon etc.
 

Plus de JAX London

Everything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityEverything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityJAX London
 
Devops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisDevops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisJAX London
 
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsBusy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsJAX London
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerJAX London
 
Java performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJava performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJAX London
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfHTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfJAX London
 
Play framework 2 : Peter Hilton
Play framework 2 : Peter HiltonPlay framework 2 : Peter Hilton
Play framework 2 : Peter HiltonJAX London
 
Complexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundComplexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundJAX London
 
Why FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberWhy FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberJAX London
 
Akka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerAkka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerJAX London
 
NoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundNoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundJAX London
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJAX London
 
Mongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsMongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsJAX London
 
New opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonNew opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonJAX London
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaJAX London
 
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerThe Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerJAX London
 
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...JAX London
 
No Crash Allowed - Patterns for fault tolerance : Uwe Friedrichsen
No Crash Allowed - Patterns for fault tolerance : Uwe FriedrichsenNo Crash Allowed - Patterns for fault tolerance : Uwe Friedrichsen
No Crash Allowed - Patterns for fault tolerance : Uwe FriedrichsenJAX London
 
Size does matter - Patterns for high scalability: Uwe Friedrichsen
Size does matter - Patterns for high scalability: Uwe FriedrichsenSize does matter - Patterns for high scalability: Uwe Friedrichsen
Size does matter - Patterns for high scalability: Uwe FriedrichsenJAX London
 

Plus de JAX London (20)

Everything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexityEverything I know about software in spaghetti bolognese: managing complexity
Everything I know about software in spaghetti bolognese: managing complexity
 
Devops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick DeboisDevops with the S for Sharing - Patrick Debois
Devops with the S for Sharing - Patrick Debois
 
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript AppsBusy Developer's Guide to Windows 8 HTML/JavaScript Apps
Busy Developer's Guide to Windows 8 HTML/JavaScript Apps
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Java performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha GeeJava performance: What's the big deal? - Trisha Gee
Java performance: What's the big deal? - Trisha Gee
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias WessendorfHTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
HTML alchemy: the secrets of mixing JavaScript and Java EE - Matthias Wessendorf
 
Play framework 2 : Peter Hilton
Play framework 2 : Peter HiltonPlay framework 2 : Peter Hilton
Play framework 2 : Peter Hilton
 
Complexity theory and software development : Tim Berglund
Complexity theory and software development : Tim BerglundComplexity theory and software development : Tim Berglund
Complexity theory and software development : Tim Berglund
 
Why FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave GruberWhy FLOSS is a Java developer's best friend: Dave Gruber
Why FLOSS is a Java developer's best friend: Dave Gruber
 
Akka in Action: Heiko Seeburger
Akka in Action: Heiko SeeburgerAkka in Action: Heiko Seeburger
Akka in Action: Heiko Seeburger
 
NoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim BerglundNoSQL Smackdown 2012 : Tim Berglund
NoSQL Smackdown 2012 : Tim Berglund
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk Pepperdine
 
Mongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdamsMongo DB on the JVM - Brendan McAdams
Mongo DB on the JVM - Brendan McAdams
 
New opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian RobinsonNew opportunities for connected data - Ian Robinson
New opportunities for connected data - Ian Robinson
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
 
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian PloskerThe Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
The Big Data Con: Why Big Data is a Problem, not a Solution - Ian Plosker
 
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
Bluffers guide to elitist jargon - Martijn Verburg, Richard Warburton, James ...
 
No Crash Allowed - Patterns for fault tolerance : Uwe Friedrichsen
No Crash Allowed - Patterns for fault tolerance : Uwe FriedrichsenNo Crash Allowed - Patterns for fault tolerance : Uwe Friedrichsen
No Crash Allowed - Patterns for fault tolerance : Uwe Friedrichsen
 
Size does matter - Patterns for high scalability: Uwe Friedrichsen
Size does matter - Patterns for high scalability: Uwe FriedrichsenSize does matter - Patterns for high scalability: Uwe Friedrichsen
Size does matter - Patterns for high scalability: Uwe Friedrichsen
 

Closures, the next "Big Thing" in Java: Russel Winder

  • 1. Closures The Next “Big Thing” in Java Russel Winder email: russel@winder.org.uk xmpp: russel@winder.org.uk twitter: @russel_winder Copyright © 2012 Russel Winder 1
  • 2. Closures The Next “Big Thing” in Java? Russel Winder email: russel@winder.org.uk xmpp: russel@winder.org.uk twitter: @russel_winder Copyright © 2012 Russel Winder 2
  • 3. Aims, Goals and Objectives ● Investigate why some idioms from Java 0–7 lead to bad code in a post-Java 7 world. ● Show what some of the idioms of Java 8 and beyond are likely to be. ● Survive to the end of the session. Copyright © 2012 Russel Winder 3
  • 4. Structure A beginning. A middle. An end. Copyright © 2012 Russel Winder 4
  • 6. A Beginning Copyright © 2012 Russel Winder 6
  • 7. Many people are still using Java 1.4. Copyright © 2012 Russel Winder 7
  • 8. They see no reason to move to any later version of Java: no real benefit, for too much pain. Copyright © 2012 Russel Winder 8
  • 9. Java 5 is a barrier too far for them. Copyright © 2012 Russel Winder 9
  • 10. The Java 7 → Java 8 change is an even more disruptive change. Copyright © 2012 Russel Winder 10
  • 11. This possibly means Java is now a legacy language? Copyright © 2012 Russel Winder 11
  • 12. No, it's an opportunity to stop programming using 1970s techniques and start using 1930s ones. Copyright © 2012 Russel Winder 12
  • 13. Alonzo Church Alan Turing Stephen Kleene J B Rosser Copyright © 2012 Russel Winder 13
  • 14. And an opportunity to do 1990s programming. Copyright © 2012 Russel Winder 14
  • 15. i.e. We finally get to do real object-oriented programming using Java. Copyright © 2012 Russel Winder 15
  • 16. Another Beginning Copyright © 2012 Russel Winder 16
  • 17. What is a “closure”? Copyright © 2012 Russel Winder 17
  • 18. A closure is a function with an associated environment containing values for all the free variables in the function. Copyright © 2012 Russel Winder 18
  • 19. A Function Integer f(final Integer x) { return x * y ; } Free variable. Copyright © 2012 Russel Winder 19
  • 20. A closure should be referentially transparent. Whenever function f is evaluated on the same value, a say, then the same value is returned. f(a) = b Copyright © 2012 Russel Winder 20
  • 21. Java has had things (sort of) like this since (almost) the beginning… Copyright © 2012 Russel Winder 21
  • 22. A closure can be realized as an instance of a class with a single method and single assignment fields. Copyright © 2012 Russel Winder 22
  • 23. public class ClosureClass { private final Integer multiplier; public ClosureClass(final Integer m) { multiplier = m; } public Integer call(final Integer i) { return multiplier * i; } } No free variables in call. Copyright © 2012 Russel Winder 23
  • 24. final ClosureClass multiplyBy5 = new ClosureClass(5); multiplyBy5.call(4) Copyright © 2012 Russel Winder 24
  • 26. public interface ClosureInterface<T> { T call(T t); } final ClosureInterface<Integer> multiplyBy5 = new ClosureInterface<Integer>() { public Integer call(final Integer i) { return 5 * i; } }; multiplyBy5.call(4) Copyright © 2012 Russel Winder 26
  • 27. If Java had operator overloading, this could be made to look much nicer. Copyright © 2012 Russel Winder 27
  • 28. Just as it can in proper programming languages such as Groovy, Scala, C++, Python, etc. Copyright © 2012 Russel Winder 28
  • 29. final multiplyBy5 = {i -> 5 * i} final multiplyBy5 = {5 * it} multiplyBy5(4) multiplyBy5.call(4) Copyright © 2012 Russel Winder 29
  • 30. def multiplyBy5(i: Int): Int = 5 * i multiplyBy5(4) Copyright © 2012 Russel Winder 30
  • 31. But Java 8 can do stuff a bit like that… Copyright © 2012 Russel Winder 31
  • 32. final ClosureInterface<Integer> multiplyBy5 = i -> 5 * i; multiplyBy5.call(4) Copyright © 2012 Russel Winder 32
  • 33. Nothing much revolutionary here, just a bit of syntactic sugar… Copyright © 2012 Russel Winder 33
  • 34. …true, but that isn't all there is… Copyright © 2012 Russel Winder 34
  • 35. A Middle Copyright © 2012 Russel Winder 35
  • 36. It all about where the iteration is. Copyright © 2012 Russel Winder 36
  • 37. Explicit iteration vs. Implicit iteration Copyright © 2012 Russel Winder 37
  • 38. Work with a (trivial) example: Copyright © 2012 Russel Winder 38
  • 39. Calculate the sum of the squares of the numbers between 0 and 100 that are divisible by 7. Copyright © 2012 Russel Winder 39
  • 40. final List<Integer> numbers = new ArrayList<>(); for (int i = 0; i < 100; ++i) { if (i % 7 == 0) { numbers.add(i); } } Integer sum = 0 ; for (final Integer i: numbers) { sum += i * i; } Copyright © 2012 Russel Winder 40
  • 41. (for (i <- 0 until 100; if i % 7 == 0) yield i * i).sum Copyright © 2012 Russel Winder 41
  • 42. sum(i * i for i in range(100) if i % 7 == 0) Copyright © 2012 Russel Winder 42
  • 43. (0 until 100).filter(i => i %7 == 0).map(i => i * i).sum Copyright © 2012 Russel Winder 43
  • 44. (0..100).findAll{i -> i % 7 == 0}.collect{i -> i * i}.sum() Copyright © 2012 Russel Winder 44
  • 45. (0..100).findAll{it % 7 == 0}.collect{it * it}.sum() Copyright © 2012 Russel Winder 45
  • 46. numbers.filter(i -> i % 7 == 0).map(i -> i * i).reduce(0, (t, x) -> t + x) Huh? Copyright © 2012 Russel Winder 46
  • 47. final List<Integer> numbers = new ArrayList<>(); for (int i = 0; i < 100; ++i) { numbers.add(i); } Oh ffs. Copyright © 2012 Russel Winder 47
  • 48. Higher Order Functions Copyright © 2012 Russel Winder 48
  • 49. Functions that take functions as parameters and/or return functions as result. Copyright © 2012 Russel Winder 49
  • 50. Some may be thinking: Why do I give a f### Copyright © 2012 Russel Winder 50
  • 51. After all nothing good has happened in Java since Java 1.4.2. Copyright © 2012 Russel Winder 51
  • 52. Copyright © 2012 Russel Winder 52
  • 53. Because all computers are now parallel computers. Copyright © 2012 Russel Winder 53
  • 54. Copyright © 2012 Russel Winder 54
  • 55. We have to move to an attitude where we assume our software is not uniprocessor. Copyright © 2012 Russel Winder 55
  • 56. We have to actually do object-oriented and functional programming. Copyright © 2012 Russel Winder 56
  • 57. Instead of just saying we write Java and so are doing object-oriented programming. Copyright © 2012 Russel Winder 57
  • 58. numbers.parallel().filter(i -> i % 7 == 0). map(i -> i * i).reduce(0, (t, x) -> t + x) Copyright © 2012 Russel Winder 58
  • 59. GParsPool.withPool { value = (0..100).findAllParallel{it % 7 == 0}.collectParallel{it * it}.sum() } Copyright © 2012 Russel Winder 59
  • 60. GParsPool.withPool { value = (0..100).parallel.filter{it % 7 == 0}.map{it * it}.sum() } Very Java 8. Copyright © 2012 Russel Winder 60
  • 61. def value = (0..100) ParallelEnhancer.enhanceInstance(value) value = value.parallel.filter{it % 7 == 0}.map{it * it}.sum() Copyright © 2012 Russel Winder 61
  • 62. def value = (0..100) ParallelEnhancer.enhanceInstance(value) value = value.findAllParallel{it % 7 == 0}.collectParallel{it * it}.sum() Copyright © 2012 Russel Winder 62
  • 63. GPars and Groovy give you Java 8 style approach and parallelism today for Java with JDK6 or JDK7. Copyright © 2012 Russel Winder 63
  • 64. Guava, TotallyLazy, and FunctionalJava can be used today to practice the functional approach using Java. Or just install the JDK8 Lambda release. Copyright © 2012 Russel Winder 64
  • 65. Using Scala is an option for doing functional programming*. Copyright © 2012 Russel Winder *And just ignore Java altogether. 65
  • 66. (0 until 100).par.filter(i => i %7 == 0).map(i => i * i).sum Copyright © 2012 Russel Winder 66
  • 67. An End Copyright © 2012 Russel Winder 67
  • 68. Java is about to get the functional programming aspect. Copyright © 2012 Russel Winder 68
  • 69. Java is about to become an object-oriented language. Copyright © 2012 Russel Winder 69
  • 70. Scala, Groovy, Python, C++, etc. already have object-oriented and functional. Copyright © 2012 Russel Winder 70
  • 71. It's all about how your data evolves. It's not about the flow of control. Copyright © 2012 Russel Winder 71
  • 72. It's all about sending messages to your objects, requesting activity. Copyright © 2012 Russel Winder 72
  • 73. Closure the next “big thing” in Java? Copyright © 2012 Russel Winder 73
  • 74. Copyright © 2012 Russel Winder 74
  • 75. Squirrels deny parallelism. Copyright © 2012 Russel Winder 75
  • 76. Copyright © 2012 Russel Winder 76
  • 77. Yes*. *But will everyone ignore it? Copyright © 2012 Russel Winder 77
  • 78. No. Copyright © 2012 Russel Winder 78
  • 79. It is not the lambda expressions in Java 8 that is the disruptive revolution. It's the change to the Java library that is. It's all about those defender methods. Copyright © 2012 Russel Winder 79
  • 81. The End Copyright © 2012 Russel Winder 81
  • 82. Closures The Next “Big Thing” in Java? Russel Winder email: russel@winder.org.uk xmpp: russel@winder.org.uk twitter: @russel_winder Copyright © 2012 Russel Winder 82