SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

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

Más 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
 

Más 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
 

Último

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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
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
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
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
 
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
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

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!
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
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.
 
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
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
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
 
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
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

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.