16 Polymorphism

 

This chapter covers

  • What polymorphism is
  • 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 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.

Listing 16.1 Example of polymorphism in TypeScript
interface Shape {
  countSides(): number;             #1
}
 
class Triangle implements Shape {   #2
  countSides() { return 3; }
}
 
class Square implements Shape {     #2
  countSides() { return 4; }
}

16.2 Overview

16.3 Implementation

16.3.1 Deciding when to use polymorphic resources

16.3.2 Polymorphic structure

16.3.3 Polymorphic behavior

16.3.4 Why not polymorphic methods?

16.3.5 Final API definition

16.4 Trade-offs

16.5 Exercises

Summary

sitemap