SlideShare una empresa de Scribd logo
1 de 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 define 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 figure 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 figure 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 find 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 find 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 benefits, but performance
    isn’t one of them. To avoid reflection 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 define 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 defined 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 defined 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
    benefits 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

Más contenido relacionado

La actualidad más candente

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

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar a 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
 
Aspect oriented programming_with_spring
Aspect oriented programming_with_springAspect oriented programming_with_spring
Aspect oriented programming_with_springGuo Albert
 

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

Último

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"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
 

Último (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"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
 

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 define 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 figure 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 figure 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 find 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 find 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 benefits, but performance isn’t one of them. To avoid reflection 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 define 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 defined 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 defined 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 benefits 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

Notas del editor

  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