Stage 1: Problem
The Problem
You are building an HTTP client library. The basic client makes requests:
typescript
| 1 | class HttpClient { |
| 2 | async request(url: string, options: RequestOptions): Promise<Response> { |
| 3 | return fetch(url, options); |
| 4 | } |
| 5 | } |
Now you need to add behaviors:
- Logging ā log every request and response for debugging.
- Retry ā retry failed requests up to 3 times with exponential backoff.
- Caching ā cache GET responses for 5 minutes.
- Authentication ā automatically attach Bearer tokens to requests.
- Rate limiting ā throttle outbound requests to stay under API limits.
And the killer requirement: these behaviors must be composable. One service needs logging + retry. Another needs auth + caching. A third needs all five. The combination varies per use case.
How do you add optional, combinable behaviors to an object without an explosion of subclasses?