liveBook · Manning

Polymorphic method

As explained in API Design Patterns

A polymorphic method is an API method whose meaning or behavior varies according to the concrete resource type on which it operates.

A polymorphic method operates on multiple resource types through one API operation. Although this can reduce duplicated methods and request shapes, identical names or signatures do not guarantee identical behavior. Resource types may later require different validation, deletion semantics, or other operations. section 16.3.4

Evaluate a polymorphic method against these design trade-offs:

  • Convenience: one method can accept identifiers for many resource types, reducing typing and apparent API surface. section 16.3.4
  • Behavioral risk: resources that seem similar may need different rules, such as soft deletion or resource-specific validation. section 16.3.4
  • Compatibility risk: combining methods can lock resources into a shared representation that becomes difficult to change without breaking clients. section 16.4
  • Recommendation: prefer polymorphic resources when appropriate, but generally keep standard methods resource-specific. section 16.4 section 16.6

Generic deletion

A DeleteResource method mapped to a wildcard URL such as */* can delete any resource identified by an arbitrary string. The design works technically, but it assumes every resource should be deleted in the same way. A chat room, message, or other resource may instead need distinct deletion behavior, including soft deletion or validation. section 16.3.4

Listing 16.9 Polymorphic method supports behavior on different resource types
abstract class GenericApi {
  @delete("/{id=*/*}")               #1
  DeleteResource(req: DeleteResourceReqeuest): void;
}
 
interface DeleteResourceRequest {
  id: string;                        #2
}

Inspect the compact API listing showing a wildcard delete route and an identifier-based request. section 16.3.4

Use a polymorphic method only when future behavioral differences are unlikely and the resources are genuinely related. Otherwise, preserve separate resource-specific methods; the extra typing protects long-term flexibility. section 16.4 section 16.6

How API Design Patterns covers it

How deep it goes
Defines the pattern, demonstrates wildcard deletion, and stops short of implementation beyond a compact method listing.
Examples
Uses a generic DeleteResource operation with a wildcard URL and arbitrary resource identifier.
What you can do after
Evaluate whether shared API methods justify their convenience or create unacceptable constraints on future resource behavior.
How it connects
Connects polymorphic methods to polymorphic resources, resource-oriented API design, soft deletion, validation, and backward compatibility.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of API Design Patterns. The section links point to the parts of the book it draws on.