SlideShare a Scribd company logo
1 of 47
Multimethodsan introduction Aman King king@thoughtworks.com
What is it?
Multiple dispatch
Basically: a language feature
Before the details…
Some Java code snippets…
public class MultimethodsDemo {    static class Walk { }    static class Dance { }    static class Attack { }    static class Robot {        public String doThis(Walk walk) { return "I am walking..."; }        public String doThis(Dance dance) { return "Let's boogie woogie..."; }        public String doThis(Attack attack) {             throw new RuntimeException("I don't believe in violence!");        }    }    public static void main(String[] args) {        Robot robot = new Robot();System.out.println(  robot.doThis(  new Walk()   ));System.out.println(  robot.doThis(  new Dance() ));System.out.println(  robot.doThis(  new Attack()  ));    }}
I am walking...Let's boogie woogie...Exception in thread "main" java.lang.RuntimeException: I don't believe in violence!	at MultimethodsDemo$Robot.doThis(MultimethodsDemo.java:10)	at MultimethodsDemo.main(MultimethodsDemo.java:18)
Polymorphism
Overloading
public class MultimethodsDemo {    static class Walk { }    static class Dance { }    static class Attack { }    static class Robot {        public String doThis(Walk walk) { return "I am walking..."; }        public String doThis(Dance dance) { return "Let's boogie woogie..."; }        public String doThis(Attack attack) {             throw new RuntimeException("I don't believe in violence!");        }    }    public static void main(String[] args) {        Robot robot = new Robot();System.out.println(  robot.doThis(  new Walk()    ));System.out.println(  robot.doThis(  new Dance()  ));System.out.println(  robot.doThis(  new Attack()  ));    }}
import java.util.*;public class MultimethodsDemo {static interface Command {}    static class Walk implements Command { }    static class Dance implements Command { }    static class Attack implements Command { }    static class Robot {        public String doThis(Walk walk) { return "I am walking..."; }        public String doThis(Dance dance) { return "Let's boogie woogie..."; }        public String doThis(Attack attack) {             throw new RuntimeException("I don't believe in violence!");         }    }    public static void main(String[] args) {        Robot robot = new Robot();        List<Command> commands = Arrays.asList( new Walk(), 	    new Dance(), new Attack() );for ( Command command :  commands ) {System.out.println(  robot.doThis(command)  );        }    }}
MultimethodsDemo.java:20: cannot find symbolsymbol  : method doThis(MultimethodsDemo.Command)location: class MultimethodsDemo.RobotSystem.out.println(  robot.doThis(command)  );                                      ^1 error
Solution?
Satisfy the compiler!
import java.util.*;public class MultimethodsDemo {    static interface Command {}    static class Walk implements Command {}    static class Dance implements Command {}    static class Attack implements Command {}    static class Robot {        public String doThis(Walk walk) { return "I am walking..."; }        public String doThis(Dance dance) { return "Let's boogie woogie..."; }        public String doThis(Attack attack) {             throw new RuntimeException("I don't believe in violence!");         }public String doThis(Command command) {             throw new RuntimeException("Unknown command: " + command.getClass());         }    }    public static void main(String[] args) {        Robot robot = new Robot();        List<Command> commands = Arrays.asList( new Walk(), new Dance(), new Attack() );        for ( Command command :  commands ) {System.out.println(  robot.doThis(command)  );        }    }}
Made the compiler happy but…
Exception in thread "main" java.lang.RuntimeException: Unknown command: class MultimethodsDemo$Walk	at MultimethodsDemo$Robot.doThis(MultimethodsDemo.java:15)	at MultimethodsDemo.main(MultimethodsDemo.java:23)
Early Binding(compile-time)
Now what?
Forcing correct overloadingatcompile-time…
// …    static class Robot {        public String doThis(Walk walk) { return "I am walking..."; }        public String doThis(Dance dance) { return "Let's boogie woogie..."; }        public String doThis(Attack attack) {             throw new RuntimeException("I don't believe in violence!");         }        public String doThis(Command command) {             if (command instanceof Walk) { return doThis(    (Walk) command    ); }            if (command instanceof Dance) { return doThis( (Dance) command  ); }            if (command instanceof Attack) { return doThis(  (Attack) command ); }            throw new RuntimeException("Unknown command: " +command.getClass());         }    } // ...
or use Visitor pattern.
So what went wrong?
Java does early binding for overloading polymorphism
But remember…
Java does late binding (runtime)for overriding polymorphism
public class MultimethodsDemo {    static class Robot {        public String name() { return "normal robot"; }    }    static class AwesomeRobot extends Robot {        public String name() { return "awesome robot!!!"; }    }    public static void main(String[] args) {Robot robot = new Robot();Robot awesomeRobot = new AwesomeRobot();System.out.println( robot.name() );                   // normal robotSystem.out.println( awesomeRobot.name() );  // awesome robot!!!    }}
Now think ofrobot.doThis(command)asdoThis(robot, command)
C# 3.0 : Extension Methodsnamespace CustomExtensions{    public static class CustomExtensionsClass    {        public static string Times(thisobject input, int times)        {            return "don't care!";        }        public static string Times(thisstring input, int times)        {            string result = "";for(inti = 0; i < times; i++)                result += input;            return result;        }        public static intTimes(thisint input, int times)        {            return input * times;        }    }}// …using CustomExtensions;varaStringObject = "aman";  aStringObject.Times(2);    // "amanaman"varanIntObject = 3;                anIntObject.Times(2);        // 6// …
In these examples, polymorphism is based on the runtime type of a single argument: the 1st one (implicitly passed)
In other words…
Java and C# 3.0support Single Dispatch
not Double Dispatch,not Multiple Dispatch.
So what is Multiple Dispatch?
Selection aka dispatchof a method based on the runtime type of multiple arguments
Languages that support Multiple Dispatch / Multimethods: ,[object Object]
Clojure
 Perl
 Groovy
C# 4.0,[object Object]
// …Robot robot = new Robot();ICommandcommand = newWalk();robot.DoThisCommand( command );  // "I am walking... "robot.DoThis( command );                   //  Exception: "Unknown command:Walk"// …
So what is interesting about Multiple Dispatch /Multimethods?
For starters…
Thinking about…
OO as syntactic sugarfor method dispatch?
Design patterns as a way to overcome lack of language features?Visitor for Double DispatchStrategy for Closures/Lambdas

More Related Content

What's hot

Exception Handling1
Exception Handling1Exception Handling1
Exception Handling1guest739536
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in KotlinLuca Guadagnini
 
VIM for (PHP) Programmers
VIM for (PHP) ProgrammersVIM for (PHP) Programmers
VIM for (PHP) ProgrammersZendCon
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistAnton Arhipov
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift OverviewKaz Yoshikawa
 
Pseudo dynamic immutable records in C++
Pseudo dynamic immutable records in C++Pseudo dynamic immutable records in C++
Pseudo dynamic immutable records in C++ant_pt
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMsunng87
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 
Go Concurrency Basics
Go Concurrency Basics Go Concurrency Basics
Go Concurrency Basics ElifTech
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Oky Firmansyah
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageAnıl Sözeri
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)ThomasHorta
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Featurexcoda
 

What's hot (20)

Exception Handling1
Exception Handling1Exception Handling1
Exception Handling1
 
Assignment
AssignmentAssignment
Assignment
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin
 
VIM for (PHP) Programmers
VIM for (PHP) ProgrammersVIM for (PHP) Programmers
VIM for (PHP) Programmers
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
 
Pseudo dynamic immutable records in C++
Pseudo dynamic immutable records in C++Pseudo dynamic immutable records in C++
Pseudo dynamic immutable records in C++
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Go Concurrency Basics
Go Concurrency Basics Go Concurrency Basics
Go Concurrency Basics
 
Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)Introduction to modern c++ principles(part 1)
Introduction to modern c++ principles(part 1)
 
Live Updating Swift Code
Live Updating Swift CodeLive Updating Swift Code
Live Updating Swift Code
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
 
Weird Ruby
Weird RubyWeird Ruby
Weird Ruby
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 

Similar to Multimethods

About java
About javaAbout java
About javaJay Xu
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Ismar Silveira
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con GroovySoftware Guru
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mockskenbot
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsPROIDEA
 

Similar to Multimethods (20)

About java
About javaAbout java
About java
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con Groovy
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
14 thread
14 thread14 thread
14 thread
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Imagine a world without mocks
Imagine a world without mocksImagine a world without mocks
Imagine a world without mocks
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
My java file
My java fileMy java file
My java file
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Java rmi
Java rmiJava rmi
Java rmi
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
 

More from Aman King

Infusing Agility into the Java Legacy
Infusing Agility into the Java LegacyInfusing Agility into the Java Legacy
Infusing Agility into the Java LegacyAman King
 
Agile Testing Dilemmas
Agile Testing DilemmasAgile Testing Dilemmas
Agile Testing DilemmasAman King
 
From Practitioner to Coach
From Practitioner to CoachFrom Practitioner to Coach
From Practitioner to CoachAman King
 
Simple Ruby DSL Techniques: Big Project Impact!
Simple Ruby DSL Techniques: Big Project Impact!Simple Ruby DSL Techniques: Big Project Impact!
Simple Ruby DSL Techniques: Big Project Impact!Aman King
 
Paving the Way for Agile Engineering Practices
Paving the Way for Agile Engineering PracticesPaving the Way for Agile Engineering Practices
Paving the Way for Agile Engineering PracticesAman King
 
Agile Testing!
Agile Testing!Agile Testing!
Agile Testing!Aman King
 
Reducing Build Time
Reducing Build TimeReducing Build Time
Reducing Build TimeAman King
 
Agile Buzzwords in Action
Agile Buzzwords in ActionAgile Buzzwords in Action
Agile Buzzwords in ActionAman King
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over ClassesAman King
 

More from Aman King (9)

Infusing Agility into the Java Legacy
Infusing Agility into the Java LegacyInfusing Agility into the Java Legacy
Infusing Agility into the Java Legacy
 
Agile Testing Dilemmas
Agile Testing DilemmasAgile Testing Dilemmas
Agile Testing Dilemmas
 
From Practitioner to Coach
From Practitioner to CoachFrom Practitioner to Coach
From Practitioner to Coach
 
Simple Ruby DSL Techniques: Big Project Impact!
Simple Ruby DSL Techniques: Big Project Impact!Simple Ruby DSL Techniques: Big Project Impact!
Simple Ruby DSL Techniques: Big Project Impact!
 
Paving the Way for Agile Engineering Practices
Paving the Way for Agile Engineering PracticesPaving the Way for Agile Engineering Practices
Paving the Way for Agile Engineering Practices
 
Agile Testing!
Agile Testing!Agile Testing!
Agile Testing!
 
Reducing Build Time
Reducing Build TimeReducing Build Time
Reducing Build Time
 
Agile Buzzwords in Action
Agile Buzzwords in ActionAgile Buzzwords in Action
Agile Buzzwords in Action
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over Classes
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
"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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
"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...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 

Multimethods

  • 1. Multimethodsan introduction Aman King king@thoughtworks.com
  • 6. Some Java code snippets…
  • 7. public class MultimethodsDemo { static class Walk { } static class Dance { } static class Attack { } static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); } } public static void main(String[] args) { Robot robot = new Robot();System.out.println( robot.doThis( new Walk() ));System.out.println( robot.doThis( new Dance() ));System.out.println( robot.doThis( new Attack() )); }}
  • 8. I am walking...Let's boogie woogie...Exception in thread "main" java.lang.RuntimeException: I don't believe in violence! at MultimethodsDemo$Robot.doThis(MultimethodsDemo.java:10) at MultimethodsDemo.main(MultimethodsDemo.java:18)
  • 11. public class MultimethodsDemo { static class Walk { } static class Dance { } static class Attack { } static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); } } public static void main(String[] args) { Robot robot = new Robot();System.out.println( robot.doThis( new Walk() ));System.out.println( robot.doThis( new Dance() ));System.out.println( robot.doThis( new Attack() )); }}
  • 12. import java.util.*;public class MultimethodsDemo {static interface Command {} static class Walk implements Command { } static class Dance implements Command { } static class Attack implements Command { } static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); } } public static void main(String[] args) { Robot robot = new Robot(); List<Command> commands = Arrays.asList( new Walk(), new Dance(), new Attack() );for ( Command command : commands ) {System.out.println( robot.doThis(command) ); } }}
  • 13. MultimethodsDemo.java:20: cannot find symbolsymbol : method doThis(MultimethodsDemo.Command)location: class MultimethodsDemo.RobotSystem.out.println( robot.doThis(command) ); ^1 error
  • 16. import java.util.*;public class MultimethodsDemo { static interface Command {} static class Walk implements Command {} static class Dance implements Command {} static class Attack implements Command {} static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); }public String doThis(Command command) { throw new RuntimeException("Unknown command: " + command.getClass()); } } public static void main(String[] args) { Robot robot = new Robot(); List<Command> commands = Arrays.asList( new Walk(), new Dance(), new Attack() ); for ( Command command : commands ) {System.out.println( robot.doThis(command) ); } }}
  • 17. Made the compiler happy but…
  • 18. Exception in thread "main" java.lang.RuntimeException: Unknown command: class MultimethodsDemo$Walk at MultimethodsDemo$Robot.doThis(MultimethodsDemo.java:15) at MultimethodsDemo.main(MultimethodsDemo.java:23)
  • 22. // … static class Robot { public String doThis(Walk walk) { return "I am walking..."; } public String doThis(Dance dance) { return "Let's boogie woogie..."; } public String doThis(Attack attack) { throw new RuntimeException("I don't believe in violence!"); } public String doThis(Command command) { if (command instanceof Walk) { return doThis( (Walk) command ); } if (command instanceof Dance) { return doThis( (Dance) command ); } if (command instanceof Attack) { return doThis( (Attack) command ); } throw new RuntimeException("Unknown command: " +command.getClass()); } } // ...
  • 23. or use Visitor pattern.
  • 24. So what went wrong?
  • 25. Java does early binding for overloading polymorphism
  • 27. Java does late binding (runtime)for overriding polymorphism
  • 28. public class MultimethodsDemo { static class Robot { public String name() { return "normal robot"; } } static class AwesomeRobot extends Robot { public String name() { return "awesome robot!!!"; } } public static void main(String[] args) {Robot robot = new Robot();Robot awesomeRobot = new AwesomeRobot();System.out.println( robot.name() ); // normal robotSystem.out.println( awesomeRobot.name() ); // awesome robot!!! }}
  • 30. C# 3.0 : Extension Methodsnamespace CustomExtensions{ public static class CustomExtensionsClass { public static string Times(thisobject input, int times) { return "don't care!"; } public static string Times(thisstring input, int times) { string result = "";for(inti = 0; i < times; i++) result += input; return result; } public static intTimes(thisint input, int times) { return input * times; } }}// …using CustomExtensions;varaStringObject = "aman"; aStringObject.Times(2); // "amanaman"varanIntObject = 3; anIntObject.Times(2); // 6// …
  • 31. In these examples, polymorphism is based on the runtime type of a single argument: the 1st one (implicitly passed)
  • 33. Java and C# 3.0support Single Dispatch
  • 34. not Double Dispatch,not Multiple Dispatch.
  • 35. So what is Multiple Dispatch?
  • 36. Selection aka dispatchof a method based on the runtime type of multiple arguments
  • 37.
  • 41.
  • 42. // …Robot robot = new Robot();ICommandcommand = newWalk();robot.DoThisCommand( command ); // "I am walking... "robot.DoThis( command ); // Exception: "Unknown command:Walk"// …
  • 43. So what is interesting about Multiple Dispatch /Multimethods?
  • 46. OO as syntactic sugarfor method dispatch?
  • 47. Design patterns as a way to overcome lack of language features?Visitor for Double DispatchStrategy for Closures/Lambdas
  • 48. Do we really need more than Single Dispatch or at best Double Dispatch?
  • 49.
  • 52.