SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Dispatch in Clojure                             Carlo Sciolla, Product Lead @ Backbase




DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(ns aot
  (:gen-class))

(defn -main [& args]
  (dorun
   (map println (seq args))))


 javap -c aot.class

 A quick journey in function calling
 We all learn to divide our code in functions, and invoke them when it’s
 their time on the stage of data processing. We deïŹne units of
 computations, ready to be executed.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
public static void main(java.lang.String[]);
[..]
   4:! invokevirtual!#66;
[..]
   26:!invokestatic!
                   #104;
   29:!invokeinterface! #108, 2;
[..]
   44:!invokespecial!#115;    (defn -main [& args]
[..]                            (dorun
                                 (map println (seq args))))

 The JVM executes our code
 We’ll leave it to the JVM to ïŹgure out which code to actually run upon
 function call. It’s not always a straightforward job, and there are several
 ways to get to the code.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
public static void main(java.lang.String[]);
[..]
   4:! invokevirtual!#66;
[..]
   26:!invokestatic!
                   #104;
   29:!invokeinterface! #108, 2;
[..]
   44:!invokespecial!#115;
[..]

 [clojure.lang.RT] static public ISeq seq(Object coll)

 Static dispatch
 When there’s nothing to choose from, the compiler emits a static
 dispatch bytecode. All calls will always result in the same code being
 executed.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
public static void main(java.lang.String[]);
[..]
   4:! invokevirtual!#66;
[..]
   26:!invokestatic!
                   #104;
   29:!invokeinterface! #108, 2;
[..]
   44:!invokespecial!#115;
[..]



 Dynamic dispatch
 Most often the compiler can’t ïŹgure out the proper method
 implementation to call, and the runtime will get its chance to
 dynamically dispatch the call.
 DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    dispatch by arity
*    object oriented inheritance
*    multimethods
*    custom is-a hierarchies
*    protocols




    The options at hand
    Clojure provides a rich interface to dynamic dispatch, allowing
    programmers to have control over the dispatch logic at different
    degrees to ïŹnd the optimal balance on the performance trade off scale.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    dispatch by arity
*    object oriented inheritance (defn sum-them
*    multimethods                  ([x y] (+ x y))
*    custom is-a hierarchies       ([x y z] (+ x y z)))
*    protocols




    The good old arity
    Being a dynamically typed language, Clojure only checks on the
    number of arguments provided in the function call to ïŹnd the right
    implementation to call.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    dispatch by arity           (defn stringify [x]
*    object oriented inheritance   (.toString x))
*    multimethods
*    custom is-a hierarchies     (stringify (HashMap.)) ; “{}”
*    protocols                   (stringify (HashSet.)) ; “[]”




    More than Javaℱ
    Thanks to Clojure intimacy with Java, object inheritance is easily
    achieved. Thanks to Clojure dynamic typing, it also allows functions to
    traverse multiple inheritance trees.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defn stringify*
                                                      [^HashMap x]
                                                      (.toString x))
*    dispatch by arity
*    object oriented inheritance
                                 (stringify* (HashMap.))
*    multimethods
                                 => “{}”
*    custom is-a hierarchies
                                 (stringify* (TreeMap.))
*    protocols
                                 => “{}”
                                 (stringify* (HashSet.))
                                 => ClassCastException


    Forcing virtual dispatch to improve performance
    Being a dynamic language has a number of beneïŹts, but performance
    isn’t one of them. To avoid reïŹ‚ection calls needed by default by the
    dynamic dispatch you can use type hints.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defn dispatch-fn
                                                      [{:keys [version]}]
*    dispatch by arity
                                                      version)
*    object oriented inheritance
*    multimethods
                                 (defmulti multi-call
*    custom is-a hierarchies
                                   dispatch-fn)
*    protocols
                                                    http://bit.ly/multi-tests



    Full power
    Multimethods allow you to deïŹne your own dispatch strategy as a plain
    Clojure function. Their limit is the sky: they perform quite bad, and your
    dispatch fn can’t be changed or extended in user code.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defmethod
                                                      multi-call ::custom-type
*    dispatch by arity
                                                      [x] [...])
*    object oriented inheritance
*    multimethods
                                 (derive java.util.HashSet
*    custom is-a hierarchies
                                   ::custom-type)
*    protocols
                                                    http://bit.ly/multi-tests



    Inheritance Ă  la carte
    Java types hierarchies deïŹned outside your code can be “altered” by
    custom is-a? relationships created as needed. You can either use the
    default hierarchy or use make-hierarchy to restrict its scope.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
(defprotocol Registered
                                                      (register [this]))
*    dispatch by arity
*    object oriented inheritance
                                 (extend-type String
*    multimethods
                                   Registered
*    custom is-a hierarchies
                                   (register [this] [...]))
*    protocols
                                                    http://bit.ly/proto-tests



    Inheritance Ă  la carte
    Java types hierarchies deïŹned outside your code can be “altered” by
    custom is-a? relationships created as needed. You can either use the
    default hierarchy or use make-hierarchy to restrict its scope.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
*    never used when compiling pure Java
*    moves type checking at run time
*    the compiler doesn’t resolve the method
*    user code to perform the dispatch
*    eligible for JIT optimizations



    http://bit.ly/headius-invokedynamic

    Bonus track: invokedynamic
    Java7 introduced a new bytecode instruction to help JVM languages
    designers: invokedynamic. There’s a long standing discussion as which
    beneïŹts it can provide to Clojure.
    DISPATCH IN CLOJURE | August 8, 2012 | @skuro
Q/A

DISPATCH IN CLOJURE | August 8, 2012 | @skuro
Thanks!
                                                  Amsterdam Clojurians
                Carlo Sciolla
                Product Lead




             http://skuro.tk
            @skuro
                                                http://bit.ly/amsclojure



DISPATCH IN CLOJURE | August 8, 2012 | @skuro

Weitere Àhnliche Inhalte

Was ist angesagt?

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder RubyNick Sieger
 
æœćŠĄæĄ†æž¶: Thrift & PasteScript
æœćŠĄæĄ†æž¶: Thrift & PasteScriptæœćŠĄæĄ†æž¶: Thrift & PasteScript
æœćŠĄæĄ†æž¶: Thrift & PasteScriptQiangning Hong
 
API management with Taffy and API Blueprint
API management with Taffy and API BlueprintAPI management with Taffy and API Blueprint
API management with Taffy and API BlueprintKai Koenig
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalKent Ohashi
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendSymfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendKirill Chebunin
 
High Performance tDiary
High Performance tDiaryHigh Performance tDiary
High Performance tDiaryHiroshi SHIBATA
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the BeastBastian Feder
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-pythonEric Ahn
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Puppet
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secretsBastian Feder
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupKacper Gunia
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesPuppet
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 

Was ist angesagt? (19)

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
æœćŠĄæĄ†æž¶: Thrift & PasteScript
æœćŠĄæĄ†æž¶: Thrift & PasteScriptæœćŠĄæĄ†æž¶: Thrift & PasteScript
æœćŠĄæĄ†æž¶: Thrift & PasteScript
 
API management with Taffy and API Blueprint
API management with Taffy and API BlueprintAPI management with Taffy and API Blueprint
API management with Taffy and API Blueprint
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendSymfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
 
Puppet @ Seat
Puppet @ SeatPuppet @ Seat
Puppet @ Seat
 
High Performance tDiary
High Performance tDiaryHigh Performance tDiary
High Performance tDiary
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the Beast
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupScaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
Scaling Symfony2 apps with RabbitMQ - Symfony UK Meetup
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet Modules
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 

Andere mochten auch

Karen White: 360
Karen White: 360Karen White: 360
Karen White: 360360mnbsu
 
Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?
Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?
Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?Darius Radkevicius
 
fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012One Columbus
 
Accounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight TransportAccounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight TransportCongressional Budget Office
 
Considering Cumulative Effects Under Nepa
Considering Cumulative Effects Under NepaConsidering Cumulative Effects Under Nepa
Considering Cumulative Effects Under NepaObama White House
 
A Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to BeA Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to Behouseofyin
 
How do we make users happy?
How do we make users happy? How do we make users happy?
How do we make users happy? martina mitz
 
Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...Browne Jacobson LLP
 
Creutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin ZulfiqarCreutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin ZulfiqarDr. Muhammad Bin Zulfiqar
 
HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks Holger Bartel
 
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT ITWHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT ITKevin Duncan
 
Air blockchain café 2016-10-04
Air blockchain café 2016-10-04Air blockchain café 2016-10-04
Air blockchain café 2016-10-04Lykle de Vries
 
Top 16 Books Hemingway Recommends
Top 16 Books Hemingway RecommendsTop 16 Books Hemingway Recommends
Top 16 Books Hemingway RecommendsESSAYSHARK.com
 

Andere mochten auch (18)

Cyborg
CyborgCyborg
Cyborg
 
Karen White: 360
Karen White: 360Karen White: 360
Karen White: 360
 
Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?
Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?
Đ§Ń‚ĐŸ ĐČŃ‹Đ±Ń€Đ°Ń‚ŃŒ ĐŁĐșŃ€Đ°ĐžĐœĐ”? ЕĐČŃ€ĐŸŃĐŸŃŽĐ· ОлО ĐąĐ°ĐŒĐŸĐ¶Đ”ĐœĐœŃ‹Đč ĐĄĐŸŃŽĐ·?
 
fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012
 
Accounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight TransportAccounting for External Costs in Pricing Freight Transport
Accounting for External Costs in Pricing Freight Transport
 
Considering Cumulative Effects Under Nepa
Considering Cumulative Effects Under NepaConsidering Cumulative Effects Under Nepa
Considering Cumulative Effects Under Nepa
 
A Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to BeA Partner is Good to Have, but Difficult to Be
A Partner is Good to Have, but Difficult to Be
 
How do we make users happy?
How do we make users happy? How do we make users happy?
How do we make users happy?
 
Dev and Designers intro to Sketch
Dev and Designers intro to SketchDev and Designers intro to Sketch
Dev and Designers intro to Sketch
 
Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...Accountability regulation and leadership in our school system - exploring a t...
Accountability regulation and leadership in our school system - exploring a t...
 
Creutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin ZulfiqarCreutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
Creutzfeldt jakob disease Dr. Muhammad Bin Zulfiqar
 
HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks HK CodeConf 2015 - Your WebPerf Sucks
HK CodeConf 2015 - Your WebPerf Sucks
 
Fall Home Prep
Fall Home PrepFall Home Prep
Fall Home Prep
 
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT ITWHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
WHY PEOPLE BULLSHIT AND WHAT TO DO ABOUT IT
 
Air blockchain café 2016-10-04
Air blockchain café 2016-10-04Air blockchain café 2016-10-04
Air blockchain café 2016-10-04
 
Top 16 Books Hemingway Recommends
Top 16 Books Hemingway RecommendsTop 16 Books Hemingway Recommends
Top 16 Books Hemingway Recommends
 
java-oneăźè©±
java-oneăźè©±java-oneăźè©±
java-oneăźè©±
 
Facebook Analytics
Facebook AnalyticsFacebook Analytics
Facebook Analytics
 

Ähnlich wie Dispatch Methods in Clojure

Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGuillaume Laforge
 
DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖
DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖
DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖Tomoharu ASAMI
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Suportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EESuportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EERodrigo CĂąndido da Silva
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Guillaume Laforge
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your CodeDrupalDay
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol Efe
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#Chandan Gupta Bhagat
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_springGuo Albert
 

Ähnlich wie Dispatch Methods in Clojure (20)

Going to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific LanguagesGoing to Mars with Groovy Domain-Specific Languages
Going to Mars with Groovy Domain-Specific Languages
 
DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖
DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖
DIăšăƒˆăƒŹă‚€ăšă«ă‚ˆă‚‹Android開ç™șたćŠč率挖
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Suportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EESuportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EE
 
core java
core javacore java
core java
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Better Understanding OOP using C#
Better Understanding OOP using C#Better Understanding OOP using C#
Better Understanding OOP using C#
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_spring
 

KĂŒrzlich hochgeladen

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo GarcĂ­a Lavilla
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

KĂŒrzlich hochgeladen (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Dispatch Methods in Clojure

  • 1. Dispatch in Clojure Carlo Sciolla, Product Lead @ Backbase DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 2. (ns aot (:gen-class)) (defn -main [& args] (dorun (map println (seq args)))) javap -c aot.class A quick journey in function calling We all learn to divide our code in functions, and invoke them when it’s their time on the stage of data processing. We deïŹne units of computations, ready to be executed. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 3. public static void main(java.lang.String[]); [..] 4:! invokevirtual!#66; [..] 26:!invokestatic! #104; 29:!invokeinterface! #108, 2; [..] 44:!invokespecial!#115; (defn -main [& args] [..] (dorun (map println (seq args)))) The JVM executes our code We’ll leave it to the JVM to ïŹgure out which code to actually run upon function call. It’s not always a straightforward job, and there are several ways to get to the code. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 4. public static void main(java.lang.String[]); [..] 4:! invokevirtual!#66; [..] 26:!invokestatic! #104; 29:!invokeinterface! #108, 2; [..] 44:!invokespecial!#115; [..] [clojure.lang.RT] static public ISeq seq(Object coll) Static dispatch When there’s nothing to choose from, the compiler emits a static dispatch bytecode. All calls will always result in the same code being executed. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 5. public static void main(java.lang.String[]); [..] 4:! invokevirtual!#66; [..] 26:!invokestatic! #104; 29:!invokeinterface! #108, 2; [..] 44:!invokespecial!#115; [..] Dynamic dispatch Most often the compiler can’t ïŹgure out the proper method implementation to call, and the runtime will get its chance to dynamically dispatch the call. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 6. * dispatch by arity * object oriented inheritance * multimethods * custom is-a hierarchies * protocols The options at hand Clojure provides a rich interface to dynamic dispatch, allowing programmers to have control over the dispatch logic at different degrees to ïŹnd the optimal balance on the performance trade off scale. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 7. * dispatch by arity * object oriented inheritance (defn sum-them * multimethods ([x y] (+ x y)) * custom is-a hierarchies ([x y z] (+ x y z))) * protocols The good old arity Being a dynamically typed language, Clojure only checks on the number of arguments provided in the function call to ïŹnd the right implementation to call. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 8. * dispatch by arity (defn stringify [x] * object oriented inheritance (.toString x)) * multimethods * custom is-a hierarchies (stringify (HashMap.)) ; “{}” * protocols (stringify (HashSet.)) ; “[]” More than Javaℱ Thanks to Clojure intimacy with Java, object inheritance is easily achieved. Thanks to Clojure dynamic typing, it also allows functions to traverse multiple inheritance trees. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 9. (defn stringify* [^HashMap x] (.toString x)) * dispatch by arity * object oriented inheritance (stringify* (HashMap.)) * multimethods => “{}” * custom is-a hierarchies (stringify* (TreeMap.)) * protocols => “{}” (stringify* (HashSet.)) => ClassCastException Forcing virtual dispatch to improve performance Being a dynamic language has a number of beneïŹts, but performance isn’t one of them. To avoid reïŹ‚ection calls needed by default by the dynamic dispatch you can use type hints. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 10. (defn dispatch-fn [{:keys [version]}] * dispatch by arity version) * object oriented inheritance * multimethods (defmulti multi-call * custom is-a hierarchies dispatch-fn) * protocols http://bit.ly/multi-tests Full power Multimethods allow you to deïŹne your own dispatch strategy as a plain Clojure function. Their limit is the sky: they perform quite bad, and your dispatch fn can’t be changed or extended in user code. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 11. (defmethod multi-call ::custom-type * dispatch by arity [x] [...]) * object oriented inheritance * multimethods (derive java.util.HashSet * custom is-a hierarchies ::custom-type) * protocols http://bit.ly/multi-tests Inheritance Ă  la carte Java types hierarchies deïŹned outside your code can be “altered” by custom is-a? relationships created as needed. You can either use the default hierarchy or use make-hierarchy to restrict its scope. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 12. (defprotocol Registered (register [this])) * dispatch by arity * object oriented inheritance (extend-type String * multimethods Registered * custom is-a hierarchies (register [this] [...])) * protocols http://bit.ly/proto-tests Inheritance Ă  la carte Java types hierarchies deïŹned outside your code can be “altered” by custom is-a? relationships created as needed. You can either use the default hierarchy or use make-hierarchy to restrict its scope. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 13. * never used when compiling pure Java * moves type checking at run time * the compiler doesn’t resolve the method * user code to perform the dispatch * eligible for JIT optimizations http://bit.ly/headius-invokedynamic Bonus track: invokedynamic Java7 introduced a new bytecode instruction to help JVM languages designers: invokedynamic. There’s a long standing discussion as which beneïŹts it can provide to Clojure. DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 14. Q/A DISPATCH IN CLOJURE | August 8, 2012 | @skuro
  • 15. Thanks! Amsterdam Clojurians Carlo Sciolla Product Lead http://skuro.tk @skuro http://bit.ly/amsclojure DISPATCH IN CLOJURE | August 8, 2012 | @skuro

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n