What is the difference between polymorphism and duck typing? - oop

I'm a little confused with the two terms, here's what I know:
Polymorphism is the ability of object of different types to be handled by a common interface. While duck typing, is a kind of dynamic typing that allows objects of different types to respond to the same methods.
From what I understand, polymorphism is more about creating an interface that can be shared across different classes. And duck typing is about loose typing that will allow methods to be called as long as it is found on the receiver of the message.
Is this correct? I'm pretty confused on the two, they seem related but I do not know what their relationship is. Thanks a lot in advance!

Polymorphism (in the context of object-oriented programming) means a subclass can override a method of the base class. This means a method of a class can do different things in subclasses. For example: a class Animal can have a method talk() and the subclasses Dog and Cat of Animal can let the method talk() make different sounds.
Duck typing means code will simply accept any object that has a particular method. Let's say we have the following code: animal.quack(). If the given object animal has the method we want to call then we're good (no additional type requirements needed). It does not matter whether animal is actually a Duck or a different animal which also happens to quack. That's why it is called duck typing: if it looks like a duck (e.g., it has a method called quack() then we can act as if that object is a duck).
So are these related? They are simply separate features that a programming language may have. There are programming languages which have polymorphism but that do not have duck typing (such as Java). There are also languages that have polymorphism and duck typing (such as Python).

This is an example for Polymorphism in Python.
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]
for animal in animals:
print(animal)
print(animal.name + ': ' + animal.talk())
This is an example for duck Typing in Python.
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and gray feathers.")
def name(self):
print("ITS A DUCK NO NAME")
class Person:
def quack(self):
print("The person imitates a duck.")
def feathers(self):
print("The person takes a feather from the ground and shows it.")
def name(self):
print("John Smith")
def in_the_forest(duck):
duck.quack()
duck.feathers()
duck.name()
def game():
for element in [Duck(), Person()]:
in_the_forest(element)
game()
In polymorphism we see subclass (Cat and Dog) inheriting from the parent class (Animal) and overriding the method Talk.
In case of duck typing we don’t create a subclass instead new class is created with method having same name but different function.

Short Answer:
Duck typing is one way of achieving Polymorphism.
Another way is by using static typing.
Long Answer:
There are two different concepts involved here, typing and programming technique.
Duck typing is a type of typing. And typing means when to throw error when an object passed around isn't what is expected. Duck typing is a kind of typing where it throws error when the program is running and the method being called isn't available. Static typing comes with compile time checking, so if the type info doesn't match, it will throw error when you compile the code. And that is typing.
Polymorphism is a programming technique where you allow multiple types of object to fulfill certain responsibilities. You can do that by using a base type to represent all the child class types. You can use duck typing to represent all the different types that have the needed methods. You can use an interface to represent all the types that implement the interface.
There are answers saying polymorphism is inheritance, and that is not correct. Although you can use inheritance to create polymorphic behavior and usually that's what you do, but that's not what polymorphism is about.
For one, you don't need inheritance to have polymorphism as described above.
Secondly, the term "Polymorphism" is more meaningful in the context of the client code that depends on abstraction, and not the implementation code. Just because you have a super class and a few other classes that inherit from it and overriding some methods does not mean it's polymorphism, to create polymorphism you have to write client code in a polymorphic way to consume these classes.

Two type Polymorphism
Method overloading(Compile time Polymorphism ).
Method overriding(Run Time Polymorphism ).
Method overloading :- same function name and different data type is known as Method overloading
Example :
int addTwovalues(int a, int b)
{ return (a+b)}
float addTwovalues(float a, float b)
{ return (a+b)}
Method overriding :- same function name and same data type but different Class
is known as Method overriding.
class a
{
virtual int addtwovalues()
{ // to do }
}
class b:a
{
override int addtwovalues()
{ // to do }
}
a obj=new a();
obj.addtwovalues();
b objb=new a();
objb.addtwovalues(); //run time Polymorphism

Related

What are sealed classes in Kotlin?

I'm a beginner in Kotlin and recently read about Sealed Classes. But from the doc the only think I actually get is that they are exist.
The doc stated, that they are "representing restricted class hierarchies". Besides that I found a statement that they are enums with superpower. Both aspects are actually not clear.
So can you help me with the following questions:
What are sealed classes and what is the idiomatic way of using ones?
Does such a concept present in other languages like Python, Groovy or C#?
UPDATE:
I carefully checked this blog post and still can't wrap my head around that concept. As stated in the post
Benefit
The feature allows us to define class hierarchies that are
restricted in their types, i.e. subclasses. Since all subclasses need
to be defined inside the file of the sealed class, there’s no chance
of unknown subclasses which the compiler doesn’t know about.
Why the compiler doesn't know about other subclasses defined in other files? Even IDE knows that. Just press Ctrl+Alt+B in IDEA on, for instance, List<> definition and all implementations will be shown even in other source files. If a subclass can be defined in some third-party framework, which not used in the application, why should we care about that?
Say you have a domain (your pets) where you know there is a definite enumeration (count) of types. For example, you have two and only two pets (which you will model with a class called MyPet). Meowsi is your cat and Fido is your dog.
Compare the following two implementations of that contrived example:
sealed class MyPet
class Meowsi : MyPet()
class Fido : MyPet()
Because you have used sealed classes, when you need to perform an action depending on the type of pet, then the possibilities of MyPet are exhausted in two and you can ascertain that the MyPet instance will be exactly one of the two options:
fun feed(myPet: MyPet): String {
return when(myPet) {
is Meowsi -> "Giving cat food to Meowsi!"
is Fido -> "Giving dog biscuit to Fido!"
}
}
If you don't use sealed classes, the possibilities are not exhausted in two and you need to include an else statement:
open class MyPet
class Meowsi : MyPet()
class Fido : MyPet()
fun feed(myPet: MyPet): String {
return when(myPet) {
is Mewosi -> "Giving cat food to Meowsi!"
is Fido -> "Giving dog biscuit to Fido!"
else -> "Giving food to someone else!" //else statement required or compiler error here
}
}
In other words, without sealed classes there is not exhaustion (complete coverage) of possibility.
Note that you could achieve exhaustion of possiblity with Java enum however these are not fully-fledged classes. For example, enum cannot be subclasses of another class, only implement an interface (thanks EpicPandaForce).
What is the use case for complete exhaustion of possibilities? To give an analogy, imagine you are on a tight budget and your feed is very precious and you want to ensure you don't end up feeding extra pets that are not part of your household.
Without the sealed class, someone else in your home/application could define a new MyPet:
class TweetiePie : MyPet() //a bird
And this unwanted pet would be fed by your feed method as it is included in the else statement:
else -> "Giving food to someone else!" //feeds any other subclass of MyPet including TweetiePie!
Likewise, in your program exhaustion of possibility is desirable because it reduces the number of states your application can be in and reduces the possibility of bugs occurring where you have a possible state where behaviour is poorly defined.
Hence the need for sealed classes.
Mandatory else
Note that you only get the mandatory else statement if when is used as an expression. As per the docs:
If [when] is used as an expression, the value of the satisfied branch becomes the value of the overall expression [... and] the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions
This means you won't get the benefit of sealed classes for something like this):
fun feed(myPet: MyPet): Unit {
when(myPet) {
is Meowsi -> println("Giving cat food to Meowsi!") // not an expression so we can forget about Fido
}
}
To get exhaustion for this scenario, you would need to turn the statement into an expression with return type.
Some have suggested an extension function like this would help:
val <T> T.exhaustive: T
get() = this
Then you can do:
fun feed(myPet: MyPet): Unit {
when(myPet) {
is Meowsi -> println("Giving cat food to Meowsi!")
}.exhaustive // compiler error because we forgot about Fido
}
Others have suggested that an extension function pollutes the namespace and other workarounds (like compiler plugins) are required.
See here for more about this problem.
Sealed classes are easier to understand when you understand the kinds of problems they aim to solve. First I'll explain the problems, then I'll introduce the class hierarchies and the restricted class hierarchies step by step.
We'll take a simple example of an online delivery service where we use three possible states Preparing, Dispatched and Delivered to display the current status of an online order.
Problems
Tagged class
Here we use a single class for all the states. Enums are used as type markers. They are used for tagging the states Preparing, Dispatched and Delivered :
class DeliveryStatus(
val type: Type,
val trackingId: String? = null,
val receiversName: String? = null) {
enum class Type { PREPARING, DISPATCHED, DELIVERED }
}
The following function checks the state of the currently passed object with the help of enums and displays the respective status:
fun displayStatus(state: DeliveryStatus) = when (state.type) {
PREPARING -> print("Preparing for dispatch")
DISPATCHED -> print("Dispatched. Tracking ID: ${state.trackingId ?: "unavailable"}")
DELIVERED -> print("Delivered. Receiver's name: ${state.receiversName ?: "unavailable"}")
}
As you can see, we are able to display the different states properly. We also get to use exhaustive when expression, thanks to enums. But there are various problems with this pattern:
Multiple responsibilities
The class DeliveryStatus has multiple responsibilities of representing different states. So it can grow bigger, if we add more functions and properties for different states.
More properties than needed
An object has more properties than it actually needs in a particular state. For example, in the function above, we don't need any property for representing the Preparing state. The trackingId property is used only for the Dispatched state and the receiversName property is concerned only with the Delivered state. The same is true for functions. I haven't shown functions associated with states to keep the example small.
No guarantee of consistency
Since these unused properties can be set from unrelated states, it's hard to guarantee the consistency of a particular state. For example, one can set the receiversName property on the Preparing state. In that case, the Preparing will be an illegal state, because we can't have a receiver's name for the shipment that hasn't been delivered yet.
Need to handle null values
Since not all properties are used for all states, we have to keep the properties nullable. This means we also need to check for the nullability. In the displayStatus() function we check the nullability using the ?:(elvis) operator and show unavailable, if that property is null. This complicates our code and reduces readability. Also, due to the possibility of a nullable value, the guarantee for consistency is reduced further, because the null value of receiversName in Delivered is an illegal state.
Introducing Class Hierarchies
Unrestricted class hierarchy: abstract class
Instead of managing all the states in a single class, we separate the states in different classes. We create a class hierarchy from an abstract class so that we can use polymorphism in our displayStatus() function:
abstract class DeliveryStatus
object Preparing : DeliveryStatus()
class Dispatched(val trackingId: String) : DeliveryStatus()
class Delivered(val receiversName: String) : DeliveryStatus()
The trackingId is now only associated with the Dispatched state and receiversName is only associated with the Delivered state. This solves the problems of multiple responsibilities, unused properties, lack of state consistency and null values.
Our displayStatus() function now looks like the following:
fun displayStatus(state: DeliveryStatus) = when (state) {
is Preparing -> print("Preparing for dispatch")
is Dispatched -> print("Dispatched. Tracking ID: ${state.trackingId}")
is Delivered -> print("Delivered. Received by ${state.receiversName}")
else -> throw IllegalStateException("Unexpected state passed to the function.")
}
Since we got rid of null values, we can be sure that our properties will always have some values. So now we don't need to check for null values using the ?:(elvis) operator. This improves code readability.
So we solved all the problems mentioned in the tagged class section by introducing a class hierarchy. But the unrestricted class hierarchies have the following shortcomings:
Unrestricted Polymorphism
By unrestricted polymorphism I mean that our function displayStatus() can be passed a value of unlimited number of subclasses of the DeliveryStatus. This means we have to take care of the unexpected states in displayStatus(). For this, we throw an exception.
Need for the else branch
Due to unrestricted polymorphism, we need an else branch to decide what to do when an unexpected state is passed. If we use some default state instead of throwing an exception and then forget to take care of any newly added subclass, then that default state will be displayed instead of the state of the newly created subclass.
No exhaustive when expression
Since the subclasses of an abstract class can exist in different packages and compilation units, the compiler doesn't know all the possible subclasses of the abstract class. So it won't flag an error at compile time, if we forget to take care of any newly created subclasses in the when expression. In that case, only throwing an exception can help us. Unfortunately, we'll know about the newly created state only after the program crashes at runtime.
Sealed Classes to the Rescue
Restricted class hierarchy: sealed class
Using the sealed modifier on a class does two things:
It makes that class an abstract class. Since Kotlin 1.5, you can use a sealed interface too.
It makes it impossible to extend that class outside of that file. Since Kotlin 1.5 the same file restriction has been removed. Now the class can be extended in other files too but they need to be in the same compilation unit and in the same package as the sealed type.
sealed class DeliveryStatus
object Preparing : DeliveryStatus()
class Dispatched(val trackingId: String) : DeliveryStatus()
class Delivered(val receiversName: String) : DeliveryStatus()
Our displayStatus() function now looks cleaner:
fun displayStatus(state: DeliveryStatus) = when (state) {
is Preparing -> print("Preparing for Dispatch")
is Dispatched -> print("Dispatched. Tracking ID: ${state.trackingId}")
is Delivered -> print("Delivered. Received by ${state.receiversName}")
}
Sealed classes offer the following advantages:
Restricted Polymorphism
By passing an object of a sealed class to a function, you are also sealing that function, in a sense. For example, now our displayStatus() function is sealed to the limited forms of the state object, that is, it will either take Preparing, Dispatched or Delivered. Earlier it was able to take any subclass of DeliveryStatus. The sealed modifier has put a limit on polymorphism. As a result, we don't need to throw an exception from the displayStatus() function.
No need for the else branch
Due to restricted polymorphism, we don't need to worry about other possible subclasses of DeliveryStatus and throw an exception when our function receives an unexpected type. As a result, we don't need an else branch in the when expression.
Exhaustive when expression
Just like all the possible values of an enum class are contained inside the same class, all the possible subtypes of a sealed class are contained inside the same package and the same compilation unit. So, the compiler knows all the possible subclasses of this sealed class. This helps the compiler to make sure that we have covered(exhausted) all the possible subtypes in the when expression. And when we add a new subclass and forget to cover it in the when expression, it flags an error at compile time.
Note that in the latest Kotlin versions, your when is exhaustive for the when expressions as well the when statements.
Why in the same file?
The same file restriction has been removed since Kotlin 1.5. Now you can define the subclasses of the sealed class in different files but the files need to be in the same package and the same compilation unit. Before 1.5, the reason that all the subclasses of a sealed class needed to be in the same file was that it had to be compiled together with all of its subclasses for it to have a closed set of types. If the subclasses were allowed in other files, the build tools like Gradle would have to keep track of the relations of files and this would affect the performance of incremental compilation.
IDE feature: Add remaining branches
When you just type when (status) { } and press Alt + Enter, Enter, the IDE automatically generates all the possible branches for you like the following:
when (state) {
is Preparing -> TODO()
is Dispatched -> TODO()
is Delivered -> TODO()
}
In our small example there are just three branches but in a real project you could have hundreds of branches. So you save the effort of manually looking up which subclasses you have defined in different files and writing them in the when expression one by one in another file. Just use this IDE feature. Only the sealed modifier enables this.
That's it! Hope this helps you understand the essence of sealed classes.
If you've ever used an enum with an abstract method just so that you could do something like this:
public enum ResultTypes implements ResultServiceHolder {
RESULT_TYPE_ONE {
#Override
public ResultOneService getService() {
return serviceInitializer.getResultOneService();
}
},
RESULT_TYPE_TWO {
#Override
public ResultTwoService getService() {
return serviceInitializer.getResultTwoService();
}
},
RESULT_TYPE_THREE {
#Override
public ResultThreeService getService() {
return serviceInitializer.getResultThreeService();
}
};
When in reality what you wanted is this:
val service = when(resultType) {
RESULT_TYPE_ONE -> resultOneService,
RESULT_TYPE_TWO -> resultTwoService,
RESULT_TYPE_THREE -> resultThreeService
}
And you only made it an enum abstract method to receive compile time guarantee that you always handle this assignment in case a new enum type is added; then you'll love sealed classes because sealed classes used in assignments like that when statement receive a "when should be exhaustive" compilation error which forces you to handle all cases instead of accidentally only some of them.
So now you cannot end up with something like:
switch(...) {
case ...:
...
default:
throw new IllegalArgumentException("Unknown type: " + enum.name());
}
Also, enums cannot extend classes, only interfaces; while sealed classes can inherit fields from a base class. You can also create multiple instances of them (and you can technically use object if you need the subclass of the sealed class to be a singleton).

polymorphism vs inheritence as the pillars of oop

As stated here
https://standardofnorms.wordpress.com/2012/09/02/4-pillars-of-object-oriented-programming/
and as the correct answer in many job interviews - the general correct answer for the question:
"What are the 4 pillars of OOP?" is:
Abstraction
Encapsulation
Inheritance
Polymorphism
What I fail to understand is how inheritance not contained in polymorphism?
in other words, how can polymorphism be used without the use of inheritance?
The only way I know of using polymorphism is
class A{
virtual void foo(){cout<<"A";}
void bar(){cout<<"A";}
};
class B : public A{
virtual foo(){cout<<"B";}
};
A* ab = new B();
ab->foo();//prints B, using polymorphism
ab->bar();//prints A, using inheritance
A* a = new A();
a->foo();//prints A
a->bar();//prints A, obviously
As I see it, polymorphism brings with it inheritance.
Please explain why it is distinct - or why can't inheritance be discarded as a key pillar of its own. We could use polymorphism or not.
What I fail to understand is how inheritence not contained in
polymorphism?
in other words, how can polymorphism be used without the use of
inheritence?
There are 3 main types of polymorphism, and only one of them requires inheritance to work.
Ad-hoc polymorphism: This is more commonly known as function/method overloading, where multiple functions can share the same name but have different signatures. Whether or not the return type is part of the signature is language dependent.
Parametric polymorphism: in OOP, this is more commonly known as generics, where a function/method can work with multiple concrete types, and return multiple concrete types, providing compile time safety.
Subtype polymorphism: This is the one I think most people think of when they talk about polymorphism. As you know, this is when subtypes provide different implementation of their parent functions/methods.
You can read more about the different types of polymorphism from the wikipedia article here: https://en.wikipedia.org/wiki/Polymorphism_(computer_science)
As I understand the two concepts:
Inheritance
You could use inheritance without using polymorphisim. For example:
class Base {
public:
void foo();
};
class Derived : public Base {
};
int main() {
Derived d;
d.foo();
}
Here we use the common functionality of the base type in all derived types, but at no point do we do anything polymophic (we never look at the derived instance though its base interface).
Polymorphism
Polymorphism as a concept includes more than the standard inheritance based method seen most often. This is actually subtyping which is just one kind of Polymorphism.
Writing a template method is technically a form of polymophism, and function overloading another. As a concept you could argue that many other things are ways to achieve polymophism.
For example:
// This function must be given an object that has a method foo().
template <typename T> bar(T& t) {
t.foo();
}
This is polymorphic behavior without inheritance.
See: https://stackoverflow.com/a/10556406/1230538 for a really good explaination of this given by someone else.
Summary
99% you use inheritance to achieve polymorphism in most modern programming languages, but they are different concepts, and can exist/be used independently of each other.
Polymorphism without inheritance:
class A {
virtual void foo() { cout << "A"; }
};
class B {
virtual void foo() { cout << "B"; }
};
A* a = new A();
A* b = new B();
a->foo(); // prints A
b->foo(); // prints B
Both instances have the same method. So they are polymorphic. However, the method does different things because the objects are different after all.

Does adding public method to subclass violate LSP (Liskov substitution principle)?

If I add public method to subclass and a client program calls added method, client programs can't use parent object instead of subclass.
import unittest
class BaseClass(object):
def doSomething(self):
pass
class SubClass(BaseClass):
def doStuff(self):
pass
class Client(object):
def __init__(self, obj):
self.obj = obj
def do(self):
self.obj.doStuff()
class LSPTestCase(unittest.TestCase):
def test_call_subclass_method(self):
client = Client(SubClass())
client.do()
def test_call_baseclass_method(self):
client = Client(BaseClass())
with self.assertRaises(AttributeError):
client.do()
if __name__ == '__main__':
unittest.main()
This case violates LSP?
No as long as all the methods inherrited from the parent class follow the same contract as the parent then LSP is preserved.
the whole point of LSP is to be able to pass around a subclass as the parent class without any problems. It says nothing about not being able to downcast for additional functionality.
Adding a method to a subclass does not violate LSP. However, it does violate if you invoke that method by downcasting from a parent class.
Robert C. Martin states right in the beginning of his LSP / SOLID paper that:
select a function based upon the type of an object
(...) is an example of a simple violation of the Liskov Substitution Principle.
Generally, if you end up in situations where you need to downcast or use the instanceof operator, it's better to revisit the use of inheritance in favor of other approaches like composition.

emulate extendable algebraic types on scala

Traditional approach to algebraic types recommends something like it:
sealed trait CompositeType
final case class LeftBranch(left : String) extends CompositeType
final case class RightBranch(right : Int) extends CompoisteType
object Trivial extends CompositeType
The problem is that I can't extend CompositeType further to have more option (just like Double extends Float offering more accuracy and providing system for backward converting from Double to Float).
Scala gives you free to define own apply and unapply methods for building and matching instances of algebraic type.
Is there any project that tries to build framework for such types?
That may be usefull for actors metaphor. Currently actors receives untyped messages (as Any implies no type restrictions) matching known types and giving safe default for others. It breaks all type strict design of scala and restricting actors with more proper types would be really nice.
update:
Example clarifing my intentions:
sealed trait CompositeType1
final case class OtherBranch(x : Int, y : Int) extends CompositeType1
object Simple extends CompositeType1
trait ComplexChoice extends CompositionType with CompositionType1
I want to create CompositionType not as a root in type hierarchy but as one solid class. That may be extended further, mixing with other classes.
Let see some normal OOP usage:
trait ContractOne
trait ContractTwo
def method(arg : ContractOne with ContractTwo)
In this example function method need an argument that fit both contracts. What does mean contract for an algebraic type? Set of available constructors and matchers. What is natural view of extending an algebraic type? Extending set of constructors with some new values (just as Double extends Float with more precise floating point numbers)
CompositeType misses this conceptions evidiently. If I mix this two algebraic types I got set intersection instead of union. This is direct effect of chosen way for representing algebraic types as set of hierarchic subtypes. It gives more freedom to span choices outside initial types, but it lacks OOP features since inheritance is taken for element construction and may not be used for extending algebraic types itself.
Haskell has only one way for adding new choices to an algebraic type:
data CompositeType = LeftBranch String | RightBranch Int | Trivial
data CompositeType1 = OtherBranch Int Int | Simple
data ComplexChoice = CompositeType | CompositeType1
ComplexChoice is defined seamlessly in concept of haskell's data types. But handling it becomes complex, since I need reroute all methods as for composition. That's why composition is a solution in scala but troublesome and boilerplate one (if there is no compiler plugin that can generate code for composition pattern)
What I really need, is something like it:
ComplexChois condense CompositeType and CompositeType1
But object hierarchies may spawn only in one direction.
So there is need in some other way for defining algebraic types.
There is space for it since infinite expanding of original trait is not something that really needed and most such traits is used with sealed keyword. Therefore some other less powerfull mechanism than extending may be used to represent data types.
As you note, objects are the end of the line for derivation of subtypes. You could, in this case, create another level of intermediate abstract type from which to derive sub-types (singleton or otherwise) of Trivial:
sealed trait Trivial extends CompositeType
object Trivia extends Trivial { ... }
class Triviality extends Trivia(...) { ... } \
...

What's the difference between Polymorphism and Multiple Dispatch?

...or are they the same thing? I notice that each has its own Wikipedia entry: Polymorphism, Multiple Dispatch, but I'm having trouble seeing how the concepts differ.
Edit: And how does Overloading fit into all this?
Polymorphism is the facility that allows a language/program to make decisions during runtime on which method to invoke based on the types of the parameters sent to that method.
The number of parameters used by the language/runtime determines the 'type' of polymorphism supported by a language.
Single dispatch is a type of polymorphism where only one parameter is used (the receiver of the message - this, or self) to determine the call.
Multiple dispatch is a type of polymorphism where in multiple parameters are used in determining which method to call. In this case, the reciever as well as the types of the method parameters are used to tell which method to invoke.
So you can say that polymorphism is the general term and multiple and single dispatch are specific types of polymorphism.
Addendum: Overloading happens during compile time. It uses the type information available during compilation to determine which type of method to call. Single/multiple dispatch happens during runtime.
Sample code:
using NUnit.Framework;
namespace SanityCheck.UnitTests.StackOverflow
{
[TestFixture]
public class DispatchTypes
{
[Test]
public void Polymorphism()
{
Baz baz = new Baz();
Foo foo = new Foo();
// overloading - parameter type is known during compile time
Assert.AreEqual("zap object", baz.Zap("hello"));
Assert.AreEqual("zap foo", baz.Zap(foo));
// virtual call - single dispatch. Baz is used.
Zapper zapper = baz;
Assert.AreEqual("zap object", zapper.Zap("hello"));
Assert.AreEqual("zap foo", zapper.Zap(foo));
// C# has doesn't support multiple dispatch so it doesn't
// know that oFoo is actually of type Foo.
//
// In languages with multiple dispatch, the type of oFoo will
// also be used in runtime so Baz.Zap(Foo) will be called
// instead of Baz.Zap(object)
object oFoo = foo;
Assert.AreEqual("zap object", zapper.Zap(oFoo));
}
public class Zapper
{
public virtual string Zap(object o) { return "generic zapper" ; }
public virtual string Zap(Foo f) { return "generic zapper"; }
}
public class Baz : Zapper
{
public override string Zap(object o) { return "zap object"; }
public override string Zap(Foo f) { return "zap foo"; }
}
public class Foo { }
}
}
With multiple dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.
Languages with multiple dispatch make use of generic functions, which are just function declarations and aren't like generic methods, which use type parameters.
Multiple dispatch allows for subtyping polymorphism of arguments for method calls.
Single dispatch also allows for a more limited kind of polymorphism (using the same method name for objects that implement the same interface or inherit the same base class). It's the classic example of polymorphism, where you have methods that are overridden in subclasses.
Beyond that, generics provide parametric type polymorphism (i.e., the same generic interface to use with different types, even if they're not related — like List<T>: it can be a list of any type and is used the same way regardless).
Multiple Dispatch is more akin to function overloading (as seen in Java/C++), except the function invoked depends on the run-time type of the arguments, not their static type.
I've never heard of Multiple Dispatch before, but after glancing at the Wikipedia page it looks a lot like MD is a type of polymorphism, when used with the arguments to a method.
Polymorphism is essentially the concept that an object can be seen as any type that is it's base. So if you have a Car and a Truck, they can both be seen as a Vehicle. This means you can call any Vehicle method for either one.
Multiple dispatch looks similar, in that it lets you call methods with arguments of multiple types, however I don't see certain requirements in the description. First, it doesn't appear to require a common base type (not that I could imagine implementing THAT without void*) and you can have multiple objects involved.
So instead of calling the Start() method on every object in a list (which is a classic polymorphism example), you can call a StartObject(Object C) method defined elsewhere and code it to check the argument type at run time and handle it appropriately. The difference here is that the Start() method must be built into the class, while the StartObject() method can be defined outside of the class so the various objects don't need to conform to an interface.
This could be nice if the Start() method needed to be called with different arguments. Maybe Car.Start(Key carKey) vs. Missile.Start(int launchCode)
But both could be called as StartObject(theCar) or StartObject(theMissile)
Interesting concept...
if you want the conceptual equivalent of a method invocation
(obj_1, obj_2, ..., obj_n)->method
to depend on each specific type in the tuple, then you want multiple dispatch. Polymorphism corresponds to the case n=1 and is a necessary feature of OOP.
Multiple Dispatch relies on polymorphism based. Typical polymorphism encountered in C++, C#, VB.NET, etc... uses single dispatch -- i.e. the function that gets called only depends on a single class instance. Multiple dispatch relies on multiple class instances.
Multiple Dispatch is a kind of polymorphism. In Java/C#/C++, there is polymorphism through inheritance and overriding, but that is not multiple dispatch, which is based on two or more arguments (not just this, like in Java/C#/C++)