function createFrog() {
// Tadpole state, can swim but cannot walk.
return {
color: 'black',
size: 10,
speed: 5,
direction: 3.14,
swim: function () {
// ...
}
};
}
function allowFrogToWalk(frog) {
frog.walk = function () {
// ...
};
}
function allowFrogToJump(frog) {
frog.jump = function () {
// ...
};
}
function makeFrogToxic(frog) {
frog.intoxicate = function (animal) {
// ...
};
}
let frog = createFrog();
// ...
// Then when the frog reaches a certain size:
allowFrogToWalk(frog);
// After the frog spends a certain amount of time on land.
allowFrogToJump(frog);
// If frog eats a certain toxic plant.
makeFrogToxic(frog);
// ...
// Let's say our game has many different kinds of animals and we manage them
// from a single place in the code (and they can interact with each other).
// When an animal tries to go on land:
if (animal.walk) {
// ...
}
// If animal enounters an obstacle:
if (animal.jump) {
// ...
}
// When an animal tries to go on water:
if (animal.swim) {
// ...
}
// When two animals touch each other
if (touches(animalA, animalB)) {
if (animalA.intoxicate) {
animalA.intoxicate(animalB);
}
// ...
}
Doing this with a statically typed language would add a lot of unnecessary complexity.
You'd need to create a lot of types/interfaces:
- Animal (which has all the generic properties of an animal)
- WaterAnimal (which inherits from Animal and can swim but not walk)
- LandAnimal (which inherits from Animal and can walk but not swim)
- Tadpole (inherits from WaterAnimal)
- ToxicTadpole (inherits from tadpole but adds intoxicate method)
- YoungFrog (inherits from WaterAnimal and LandAnimal and is constructed from a Tadpole instance, cannot jump)
- ToxicYoungFrog (inherits from YoungFrog but adds intoxicate method)
- MatureFrog (inherits from WaterAnimal and LandAnimal and is constructed from a YoungFrog instance, has the ability to Jump)
- ToxicMatureFrog (inherits from MatureFrog but adds intoxicate method)
As you add more complex functionality, you either have to support more permutations of different types or you have come up with some kind of complex decorator pattern which subverts the whole purpose of having static types to begin with.