Notes
Requirements
Fix the scope. A limited overs match has two teams and two innings. An over is six legal balls. The scorer records runs, extras such as wides, no balls, byes and leg byes, and wickets with the way the batter got out. The strike changes after odd runs and at the end of each over. We show batting and bowling scorecards, support T20 and one day formats, let the scorer correct a wrong entry, and push updates to many viewers.
Ask the questions that change the code. Does a wide count as one of the six balls? No: it gives one run and is bowled again. A no ball also gives one run, and in limited overs cricket the next ball is a free hit. Does a run out count in the bowler's wickets? No, the other dismissals do. A bowler can never bowl two overs in a row, and can bowl at most four overs in a T20 and ten in a one day match. Test matches and rain rules are out of scope.
- two teams, two innings
- overs of six legal balls
- runs, wides, no balls, byes,
- leg byes
- wickets with how out
- strike changes on odd runs and
- at the end of an over
- batting and bowling scorecards
- formats: T20, ODI
- fix a wrongly entered ball
- live feeds for many viewers
- does a wide count as a ball?
- no: one run, ball bowled again
- no ball: one run, free hit next
- run out counts for the bowler?
- no, the other ways do
- same bowler two overs in a row?
- never
- overs per bowler: T20 four,
- ODI ten
- out of scope: Test matches,
- rain rules, ball tracking
Entities
Underline the nouns: match, team, player, innings, over, ball, wicket. A match has two teams, a format and up to two innings. A team is a name and a batting order. Here is the key insight: an over and a scorecard are not things you store. An innings is just a list of events in order, and overs, totals and scorecards are all computed from that list. Players are names in this version, so a player is not even a class yet.
Class diagram
Get the extras right, because interviewers who know cricket will check. A normal ball gives its runs to the batter. A wide adds one run plus any runs taken, is not a legal ball, does not count as a ball faced, and is charged to the bowler. A no ball adds one run, is not a legal ball, but does count as faced, and runs hit off it go to the batter. Byes and leg byes are legal balls whose runs are extras and are not charged to the bowler.
In code, a ball is a Delivery record: the kind of extra, the runs completed, and an optional dismissal with the batter who is out. Four short methods hold all the rules: is it legal, the total it adds, the runs credited to the batter, and the runs charged to the bowler. Events form a sealed interface with two kinds: a delivery, and an over started by a named bowler. Records never change, which matters later for readers.
- normal: runs to the batter
- wide: +1, not a legal ball,
- not faced, bowler charged
- no ball: +1, not legal, faced,
- bat runs go to the batter
- bye, leg bye: legal ball,
- runs are extras, not the
- bowler's fault
- legal ball: counts in the over
record Delivery(Extra extra, int runs,
Dismissal out, String outBatter, ..)
boolean legal() // not WIDE, not NO_BALL
int total() // runs, +1 if not legal
int batRuns() // NONE, NO_BALL only
int bowlerRuns() // all but byes
sealed interface Event
permits OverStarted, Delivery Event sourcing
This is event sourcing. The ball-by-ball log is the single source of truth, and it only grows. An InningsState object is a projection: it starts empty and applies events one at a time, keeping the total, wickets, legal balls, who is on strike, who is bowling, and every scorecard row. For a new ball we apply just that one event. But at any moment we could throw the state away, replay the log, and get exactly the same scoreboard. That property gives us undo almost for free.
- the log: append-only events
- InningsState: apply(event)
- total, wickets, balls,
- striker, bowler, free hit,
- every scorecard row
- new ball: validate, append,
- apply one event
- any time: replay the log from
- empty and get the same state
Strategy: format
Formats differ in their limits, so the format is a Strategy. The MatchFormat interface answers four questions: overs per innings, the most overs one bowler may bowl, balls per over, and whether a no ball gives a free hit. T20 is twenty overs and four per bowler; a one day match is fifty and ten. A club's ten over game is just a custom record. The innings code asks the format and never checks a format name.
interface MatchFormat {
int oversPerInnings();
int maxOversPerBowler();
default int ballsPerOver() { return 6; }
default boolean freeHitAfterNoBall()
{ return true; }
}
enum StandardFormat implements ..
T20(20, 4), ODI(50, 10)
record CustomFormat(..) for a
ten over game or a test run Flow: record a ball
Walk the main flow. The scorer records a four. First the state validates it: is there an over in progress, is the innings still alive, is this dismissal possible on this kind of ball? A bad entry throws before anything changes. Then the event is appended to the log with a time from an injected clock, applied to the state, and a fresh immutable snapshot is published. Finally listeners hear about the ball, and about the end of an over or innings.
synchronized void record(Delivery d) {
state.validate(d); // throws, no change
log.add(new Logged(seq, clock.get(), d));
String text = state.apply(d);
latest = state.snapshot(); // volatile
notify(BALL, text);
if (over ended) notify(OVER_END);
if (innings done) notify(INNINGS_END);
} Strike rotation
Strike rotation is where most solutions break. If the batters complete an odd number of runs they have changed ends, so we swap the striker and the non-striker. This uses runs actually run, so a wide with one run taken also swaps. After the sixth legal ball the over ends: the bowler gets a maiden if the over cost them nothing, the bowler slot is cleared so the scorer must name the next bowler, and the ends swap again, because the next over is bowled from the other end.
// runs actually completed, even on
// a wide, bye or leg bye
if (d.runs() % 2 == 1) swapEnds();
if (d.out() != null) dismiss(d);
if (d.legal() && legalBalls % 6 == 0) {
if (overRuns == 0) bowler.maidens++;
lastOverBowler = bowler;
bowler = null; // must start a new over
swapEnds();
} Wickets
Wickets have rules too. Bowled, caught, leg before, stumped and hit wicket go into the bowler's wicket column; a run out does not, and either batter can be run out. Off a wide, only stumped, run out or hit wicket are possible. Off a no ball, or on a free hit, the striker can only be run out among our types. The next batter in the order walks in and takes the place of the batter who is out, so after a catch the new batter faces the next ball.
- bowled, caught, lbw, stumped,
- hit wicket: bowler credited
- run out: not the bowler's
- wicket; either batter
- on a wide: stumped, run out,
- hit wicket only
- on a no ball: run out only
- free hit: run out only
- new batter takes the place of
- the batter who is out
Scorecards
The scorecards fall out of the replay. Each batter has runs, balls faced, fours, sixes and how they got out, and the strike rate is runs times one hundred divided by balls. Each bowler has overs, maidens, runs conceded and wickets, and the economy is runs per six balls. Overs are written like three point four, meaning three overs and four balls. A neat check: batters' runs plus extras equals the total, which also equals bowlers' runs plus byes and leg byes.
- batter: runs, balls, 4s, 6s,
- how out
- strike rate: runs x 100 / balls
- bowler: overs, maidens, runs,
- wickets
- overs shown as 3.4: three overs
- and four balls
- economy: runs x 6 / balls
- check: bat runs + extras =
- total = bowler runs + byes
Observer: live feeds
Live feeds use the Observer pattern. Each update carries a kind, a line of text such as nought point three, four runs, and the new snapshot. The commentary listener prints every ball. The scoreboard view only cares about the end of each over. A push notifier for wickets, or a feed to a TV graphics system, is one more listener. The match never knows who is listening, and the list is copy-on-write so subscribing never blocks the scorer.
enum UpdateKind { BALL, OVER_END,
CORRECTION, INNINGS_END }
record Update(kind, text, snapshot)
interface ScoreListener {
void onUpdate(Update u);
}
listeners: CopyOnWriteArrayList
Commentary: every BALL line
ScoreboardView: OVER_END only Undo a wrong ball
The scorer typed a four, but it was a six. How do we fix it? A naive design writes reverse logic for every case: take back the runs, swap the strike back, un-end the over, restore the free hit. That is a bug farm. With event sourcing we simply remove the last event and replay the log from the start. A full T20 innings is a few hundred events, so replay takes microseconds, and the result is correct by construction.
synchronized Event undo() {
Logged last = log.remove(size - 1);
state = InningsState.replay(log);
latest = state.snapshot();
notify(CORRECTION, ..);
return last.event();
}
replay of a whole T20 innings:
a few hundred events, microseconds Concurrency
Concurrency here has a clear shape: one writer, many readers. Writes are synchronized on the match, but only the scorer writes, so the lock is never contended. The mutable state is never handed out. After each write we build an immutable snapshot of records and copied lists, and publish it through a volatile field. Readers just read that field, with no lock at all, and can never see a half-applied ball, such as runs added but the strike not yet swapped.
Check every shared thing. The log and the state are touched only while holding the match lock. Snapshots are immutable and published through a volatile field. Listeners live in a copy-on-write list. We call them in order while holding the lock, so commentary lines never arrive out of order; a slow listener, like one that sends push messages, should put the update on its own queue and return quickly. Events are records, so they are safe to share anywhere.
- writes: synchronized on Match
- only the scorer, so no fight
- state: mutable, never shared
- snapshot: records + List.copyOf
- built under the lock
- published through a volatile
- field: safe publication
- readers: no lock, never see a
- half-applied ball
- log + state: only under the
- Match lock
- snapshot: immutable, volatile
- listeners: CopyOnWriteArrayList
- listeners called in order under
- the lock: slow ones hand off
- to their own queue
- fake clock: AtomicReference
- events: records, safe to share
Chase and result
The second innings gets a target: the first innings total plus one. An innings ends in three ways: ten wickets fall, the overs run out, or the chasing side reaches the target. After that the state rejects any more balls. The result follows the cricket convention: a team that chases successfully wins by the wickets it has left, a team that defends wins by the runs it was ahead, and equal scores are a tie.
boolean complete() {
return wickets >= players - 1
|| legalBalls >= overs * 6
|| (target != null
&& total >= target);
}
target = first innings total + 1
chase won: by wickets in hand
chase lost: by runs short
equal scores: a tie Extensibility
Interviewers will push on extensions. A Test match needs a format with no over limit, plus declarations and the follow-on. A super over is a short third innings. Partnerships, fall of wickets, or runs per over for a chart are each just another projection over the same log, with no change to how balls are recorded. Rain-reduced targets are a target strategy. A win predictor is another listener. The event log makes most of these cheap.
- Test match: format with no over
- limit, follow-on, declarations
- super over: a third mini innings
- fielders and keepers: a Player
- class with roles
- partnerships, fall of wickets:
- one more projection of the log
- rain rules: a TargetStrategy
- win prediction: a listener
Testing
The full code is below the player. The demo uses a two over custom format so every rule shows up in a few lines: a wide that is not a legal ball, a no ball and its free hit, a catch rejected on the free hit, a wrong four corrected to a six with undo, a bowled, a bye, a catch, a run out, and a bowler blocked from bowling twice in a row. Then the chase, the result, and a T20 innings written while three reader threads check every snapshot.
0.3 Lev to Bex: no ball + 2 runs [FREE HIT next] Rejected: free hit: only a run out 0.3 Lev to Bex: FOUR ** correction: removed FOUR 0.3 Lev to Bex: SIX Rejected: Lev cannot bowl two overs in a row Falcons 25/3 (2.0 ov) Tigers won by 10 wickets
Follow-ups
Expect follow-ups. With millions of viewers, the snapshot or each event goes to a publish and subscribe system and is cached at the edge, so viewers never touch the scorer's server. If the scorer's device goes offline, it queues events with sequence numbers and sends them later. If two scorers type at once by mistake, the server rejects an event whose sequence number is stale. And why not just store totals? Totals drift with corrections; the log does not.
- millions of viewers?
- push snapshots to a pub-sub,
- cache at the edge
- scorer phone goes offline?
- queue events, sequence numbers
- two scorers by mistake?
- reject a stale sequence
- why not store the totals?
- they drift; the log never lies
- audit: who changed which ball
Say it like this
Here is the short version to say out loud. An innings is an append-only log of balls. Totals, strike, overs and both scorecards are a projection: apply each new event, or replay the log to undo a mistake. Over and bowler limits come from a format strategy, live feeds are observers, and one scorer writes under a lock while any number of readers take an immutable snapshot published through a volatile field.
- "An innings is an append-only
- log of balls. Totals, strike,
- overs and scorecards are a
- projection: apply each event,
- or replay to undo. Formats are
- a Strategy, feeds are
- observers, one scorer writes
- under a lock and readers get an
- immutable volatile snapshot."