16 Polymorphism
This chapter covers...
- What is polymorphism?
- The benefits of polymorphism and when to use it in an API
- How best to structure polymorphic resources
- Why polymorphic methods should be avoided in resource-oriented APIs
When building software systems, polymorphism provides the ability for objects to take many different forms, typically relying on explicit object inheritance. In this pattern, we'll explore how to translate this powerful tool from the world of object-oriented programming to that of resource-oriented API design. We'll also investigate a few guidelines for when to rely on polymorphic resources over completely independent resources.
16.1 Motivation
In object-oriented programming (OOP), polymorphism is the idea of using single common interfaces across different concrete types, minimizing the implementation details that we need to understand in order to interact with a specific type. In other words, if we have class Triangle and class Square, they might both implement a common countSides() method and specify this by extending a shared interface Shape, shown in Listing 16.X.
Listing 16.X Example of polymorphism in TypeScript.
interface Shape {
countSides(): number; // #A
}
class Triangle implements Shape { // #B
countSides() { return 3; }
}
class Square implements Shape { // #B
countSides() { return 4; }
}