Part 3 of 6 · 1 min read
Classes
Driver, trip, matcher and fare rule.
| Class | Job in one sentence |
|---|---|
Point (record) |
A location with a distance method |
Driver |
Id, location and a state. Offers tryReserve, release, goOnline and goOffline |
Trip |
Id, rider, route, a state and the assigned driver. Enforces the legal moves |
Matcher (interface) |
Returns available drivers in the order they should be offered (strategy) |
NearestMatcher |
Sorts by distance to the pickup, ties by id |
FareRule (interface) |
Gives a fare in cents from distance and minutes (strategy) |
BaseFare, Surge |
A plain fare, and a decorator that multiplies another rule |
Service |
Holds drivers and trips and runs the request, start, complete and cancel steps |
Two design decisions deserve a sentence each.
First, the driver owns its own state. Only the driver can say "I am free, and now I am yours" in one atomic step. If the service read the state and then set it, two threads could do that at once, and one driver would get two trips.
Second, the matcher only ranks. It does not reserve anyone. A ranked list may already be stale when the service reads it, since another request may have taken a driver in between. So the service walks down the list and tries to reserve each driver in turn, and stops at the first success.
Check yourself: 1. Why does the driver own its state? 2. Why does the matcher return a list and not one driver? 3. Which two classes are strategies?