SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

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

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

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

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

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

Dernier

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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"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
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
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
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
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
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Dernier (20)

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
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"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
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
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
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
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
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"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...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

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.