SlideShare a Scribd company logo
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

More Related Content

What's hot

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
Nick 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 Blueprint
Kai Koenig
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
Kent 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
 
Puppet @ Seat
Puppet @ SeatPuppet @ Seat
Puppet @ Seat
Alessandro Franceschi
 
High Performance tDiary
High Performance tDiaryHigh Performance tDiary
High Performance tDiary
Hiroshi SHIBATA
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
rsebbe
 
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
Matteo Battaglio
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the Beast
Bastian Feder
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
Eric Ahn
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
Gabriele 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 Meetup
Kacper Gunia
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet Modules
Puppet
 
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
Cory Forsyth
 

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

Viewers also liked

Cyborg
CyborgCyborg
Karen White: 360
Karen White: 360Karen White: 360
Karen White: 360
360mnbsu
 
Что выбрать Украине? Евросоюз или Таможенный Союз?
Что выбрать Украине? Евросоюз или Таможенный Союз?Что выбрать Украине? Евросоюз или Таможенный Союз?
Что выбрать Украине? Евросоюз или Таможенный Союз?Darius Radkevicius
 
fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012fDi Digital Marketing Awards 2012
fDi Digital Marketing Awards 2012
One 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 Transport
Congressional 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 Be
houseofyin
 
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
 
Dev and Designers intro to Sketch
Dev and Designers intro to SketchDev and Designers intro to Sketch
Dev and Designers intro to Sketch
💻 Mark Schumacher
 
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 Zulfiqar
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
Holger Bartel
 
Fall Home Prep
Fall Home PrepFall Home Prep
Fall Home Prep
Maid Pro Tulsa, OK
 
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
Kevin Duncan
 
Air blockchain café 2016-10-04
Air blockchain café 2016-10-04Air blockchain café 2016-10-04
Air blockchain café 2016-10-04
Lykle de Vries
 
Top 16 Books Hemingway Recommends
Top 16 Books Hemingway RecommendsTop 16 Books Hemingway Recommends
Top 16 Books Hemingway Recommends
ESSAYSHARK.com
 
java-oneの話
java-oneの話java-oneの話
java-oneの話
Recruit Technologies
 
Facebook Analytics
Facebook AnalyticsFacebook Analytics
Facebook Analytics
SchoolOfMarketing
 

Viewers also liked (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 to Dispatch 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 Languages
Guillaume Laforge
 
DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化Tomoharu ASAMI
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
Heiko Behrens
 
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 EE
Rodrigo 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 developement
frwebhelp
 
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 Plugins
Paul King
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
Marco Vito Moscaritolo
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
DrupalDay
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
Birol 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'15
Murat 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
 

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

Recently uploaded

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 

Recently uploaded (20)

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

Dispatch 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

Editor's Notes

  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