Candidate submission · Software Engineer exercise
The Java fare engine I wrote for your exercise, running live in this page. Pick a card, tap the reader, drive the bus.
5500 00•• •••• 5559

The reader lets you on.The price comes later.
The brief's sample, taken apart the way TripPricer does it.
Taps 1 and 2, as the engine prints them
Edit the CSV or the fares and the engine re-runs as you type. Each rule I had to decide comes with a scenario that proves it.
tariff <operator> <id> <from: dd-MM-yyyy HH:mm:ss | *> [flat <amount>] fare <stop> <stop> <amount>
| Started | From | To | Secs | Charge | Status | Card | Tariff |
|---|
Taps are ordered by their own timestamp, never by when they arrived.
A tap off with nothing to pair it with is reported, not charged.
A second tap on leaves the first trip incomplete, at the highest fare from its stop.
A tap on and a tap off are only a trip when they share a bus and an operator.
Tap on and off at the same stop: cancelled, $0.00, with the tap off kept.
A tap resent unchanged is kept once. The copy is reported.
An ID reused with different data: neither copy is trusted, so arrival order can't change the price.
A trip touching a stop the tariff doesn't know is reported, never charged a maximum fare.
New fares are a new dated tariff. A trip is priced by the one in force when it began.
Each operator brings its own stops, fares and rule for incomplete trips.
A tariff has a start date. A trip uses the one in force when the passenger tapped on, so last month's trips price the same forever.
Ten January trips, priced with the catalogue as it was then and with today's, which has February's fares and a second operator.
FareCatalogue today = FareCatalogue.builder()
.operator("Company1", new Tariff("c1-2026-01", Instant.EPOCH, JANUARY))
.operator("Company1", new Tariff("c1-2026-02", FEB_1, FEBRUARY))
.operator("Harbour", new Tariff("hb-2026-01", Instant.EPOCH, HARBOUR,
IncompleteTripPolicy.flat("5.00")))
.build();
new TripPricer(today).price(taps); // the pricer never changesFareCatalogueTest. Adding an operator or a fare rise is data.Readers go offline, so taps turn up late, twice or out of order. Each one re-prices the card's whole day and only the difference is posted.
Prices come from the real pricer. The ledger around it is my Part 2 design, simulated here.

Scroll to let the taps arrive
Closing is the operator's maximum journey time running out. Until then a tap on is open and nothing is charged.
Try it: deliver #1, close, then deliver #2.
| Idempotency key | Delta | Because |
|---|---|---|
| Nothing posted yet. | ||

About 800k taps a day, around 100 a second at peak. Throughput is easy. Getting the charge right when taps arrive late, twice or out of order is the hard part.
Photo: Albert Stoynov / Unsplash1 / 8
The reader admits the passenger offline: a genuine card, not on the deny list. Taps queue on the bus and upload when there's signal.
Service icons: AWS Architecture Icons.
Run when this page was built, against the same source the engine above was compiled from. 13 files, 691 lines, no dependencies.
Built 2026-12-06 15:43 UTC · ./gradlew test
package dev.benzarti.fares;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Turns a list of taps into priced trips.
*
* <p>The pricer is a pure function of its input: the same taps always give the same trips, whatever
* order they arrive in and however many times a tap is repeated. That is what lets a real system
* simply re-run it when a late tap arrives (see {@code docs/DESIGN.md}).
*
* <p>Steps:
* <ol>
* <li>Keep one copy of a tap resent with identical content; reject every copy of a tap ID that
* was reused with different content.</li>
* <li>Group the remaining taps by card and sort each card's taps by time, then by ID.</li>
* <li>Walk each card's taps, pairing every tap on with the next tap if it is a tap off on the
* same bus. Anything else closes the tap on as an incomplete trip.</li>
* <li>Price each trip with the tariff of its tap-on operator in force at its tap-on time. Report,
* rather than price, any trip that touches a stop missing from that tariff.</li>
* </ol>
*/
public final class TripPricer {
private static final Comparator<Tap> CHRONOLOGICAL =
Comparator.comparing(Tap::timestamp).thenComparingLong(Tap::id);
private static final Comparator<Trip> OUTPUT_ORDER =
Comparator.comparing(Trip::started).thenComparing(trip -> trip.pan().value()).thenComparingLong(Trip::tapOnId);
/** Total order over anomalies, so two copies of a conflicting tap always come out the same way. */
private static final Comparator<Anomaly> ANOMALY_ORDER = Comparator
.comparing((Anomaly a) -> a.tap().timestamp())
.thenComparingLong(a -> a.tap().id())
.thenComparing(a -> a.reason())
.thenComparing(a -> a.tap().type())
.thenComparing(a -> a.tap().stopId())
.thenComparing(a -> a.tap().companyId())
.thenComparing(a -> a.tap().busId())
.thenComparing(a -> a.tap().pan().value());
private final FareCatalogue catalogue;
/** Prices with one fare table for every operator and all time, as in the exercise. */
public TripPricer(FareTable fares) {
this(FareCatalogue.single(Objects.requireNonNull(fares, "fares")));
}
/** Prices with per-operator, versioned tariffs. */
public TripPricer(FareCatalogue catalogue) {
this.catalogue = Objects.requireNonNull(catalogue, "catalogue");
}
public PricingResult price(List<Tap> taps) {
Objects.requireNonNull(taps, "taps");
List<Anomaly> anomalies = new ArrayList<>();
List<Tap> unique = deduplicate(taps, anomalies);
Map<String, List<Tap>> byCard = unique.stream()
.collect(Collectors.groupingBy(tap -> tap.pan().value(), LinkedHashMap::new, Collectors.toList()));
List<Trip> trips = new ArrayList<>();
for (List<Tap> cardTaps : byCard.values()) {
cardTaps.sort(CHRONOLOGICAL);
buildTrips(cardTaps, trips, anomalies);
}
trips.sort(OUTPUT_ORDER);
anomalies.sort(ANOMALY_ORDER);
return new PricingResult(trips, anomalies);
}
/**
* Readers on patchy connections resend taps, so the same tap can arrive more than once. Copies of
* a tap ID that are all identical are a harmless resend: one is kept. If any copy differs, the ID
* is a data integrity problem and <em>no</em> copy is trusted. Keeping "the first one received"
* instead would make the result depend on arrival order.
*/
private static List<Tap> deduplicate(List<Tap> taps, List<Anomaly> anomalies) {
Map<Long, List<Tap>> byId = new LinkedHashMap<>();
for (Tap tap : taps) {
byId.computeIfAbsent(tap.id(), id -> new ArrayList<>()).add(tap);
}
List<Tap> unique = new ArrayList<>();
for (List<Tap> copies : byId.values()) {
Tap first = copies.getFirst();
boolean allIdentical = copies.stream().allMatch(first::equals);
if (allIdentical) {
unique.add(first);
copies.stream().skip(1).forEach(copy -> anomalies.add(new Anomaly(copy, Anomaly.Reason.DUPLICATE_TAP)));
} else {
copies.forEach(copy -> anomalies.add(new Anomaly(copy, Anomaly.Reason.CONFLICTING_TAP_ID)));
}
}
return unique;
}
private void buildTrips(List<Tap> cardTaps, List<Trip> trips, List<Anomaly> anomalies) {
Tap openTapOn = null;
for (Tap tap : cardTaps) {
if (tap.type() == TapType.ON) {
if (openTapOn != null) {
closeIncomplete(openTapOn, trips, anomalies);
}
openTapOn = tap;
} else if (openTapOn != null && openTapOn.sameVehicleAs(tap)) {
closeFinished(openTapOn, tap, trips, anomalies);
openTapOn = null;
} else {
if (openTapOn != null) {
closeIncomplete(openTapOn, trips, anomalies);
openTapOn = null;
}
anomalies.add(new Anomaly(tap, Anomaly.Reason.TAP_OFF_WITHOUT_TAP_ON));
}
}
if (openTapOn != null) {
closeIncomplete(openTapOn, trips, anomalies);
}
}
/**
* A trip touching a stop its tariff does not know cannot be priced. Rather than guess, which for a
* tap on would mean charging the maximum fare, both taps are reported and nothing is charged.
*/
private void closeFinished(Tap on, Tap off, List<Trip> trips, List<Anomaly> anomalies) {
Tariff tariff = tariffFor(on).orElse(null);
if (tariff == null) {
anomalies.add(new Anomaly(on, Anomaly.Reason.NO_TARIFF));
anomalies.add(new Anomaly(off, Anomaly.Reason.NO_TARIFF));
return;
}
boolean onKnown = tariff.fares().knowsStop(on.stopId());
boolean offKnown = tariff.fares().knowsStop(off.stopId());
if (onKnown && offKnown) {
trips.add(finished(on, off, tariff));
return;
}
anomalies.add(new Anomaly(on, onKnown ? Anomaly.Reason.PAIRED_WITH_UNKNOWN_STOP : Anomaly.Reason.UNKNOWN_STOP));
anomalies.add(new Anomaly(off, offKnown ? Anomaly.Reason.PAIRED_WITH_UNKNOWN_STOP : Anomaly.Reason.UNKNOWN_STOP));
}
private void closeIncomplete(Tap on, List<Trip> trips, List<Anomaly> anomalies) {
Tariff tariff = tariffFor(on).orElse(null);
if (tariff == null) {
anomalies.add(new Anomaly(on, Anomaly.Reason.NO_TARIFF));
} else if (!tariff.fares().knowsStop(on.stopId())) {
anomalies.add(new Anomaly(on, Anomaly.Reason.UNKNOWN_STOP));
} else {
trips.add(incomplete(on, tariff));
}
}
private Optional<Tariff> tariffFor(Tap on) {
return catalogue.tariffFor(on.companyId(), on.timestamp());
}
private static Trip finished(Tap on, Tap off, Tariff tariff) {
boolean sameStop = on.stopId().equals(off.stopId());
TripStatus status = sameStop ? TripStatus.CANCELLED : TripStatus.COMPLETED;
BigDecimal charge = sameStop ? Money.ZERO : tariff.fares().fareBetween(on.stopId(), off.stopId());
return new Trip(on.timestamp(), off.timestamp(), on.stopId(), off.stopId(), charge,
on.companyId(), on.busId(), on.pan(), status, on.id(), off.id(), tariff.id());
}
private static Trip incomplete(Tap on, Tariff tariff) {
BigDecimal charge = tariff.incompleteTrip().charge(on.stopId(), tariff.fares());
return new Trip(on.timestamp(), null, on.stopId(), null, charge,
on.companyId(), on.busId(), on.pan(), TripStatus.INCOMPLETE, on.id(), null, tariff.id());
}
}package dev.benzarti.fares;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Every operator's tariffs over time.
*
* <p>A trip is priced with the tariff of <em>its tap-on operator</em> that was in force <em>at its
* tap-on time</em>, never the one in force when the tap happens to be processed. That keeps late taps
* and re-pricing consistent across fare changes, and lets new operators be added as data rather than
* code.
*/
public final class FareCatalogue {
/** Matches any operator; used by {@link #single(FareTable)}. */
static final String ANY_OPERATOR = "*";
private final Map<String, List<Tariff>> tariffsByOperator;
private FareCatalogue(Map<String, List<Tariff>> tariffsByOperator) {
Map<String, List<Tariff>> copy = new HashMap<>();
tariffsByOperator.forEach((operator, tariffs) -> copy.put(operator, List.copyOf(tariffs)));
this.tariffsByOperator = Map.copyOf(copy);
}
public static Builder builder() {
return new Builder();
}
/** One fare table for every operator, for all time: the exercise's setting. */
public static FareCatalogue single(FareTable fares) {
return builder().operator(ANY_OPERATOR, new Tariff("default", Instant.MIN, fares)).build();
}
/** The tariff in force for {@code operator} at {@code at}, if any. */
public Optional<Tariff> tariffFor(String operator, Instant at) {
List<Tariff> tariffs = tariffsByOperator.get(operator);
if (tariffs == null) {
tariffs = tariffsByOperator.get(ANY_OPERATOR);
}
if (tariffs == null) {
return Optional.empty();
}
Tariff inForce = null;
for (Tariff tariff : tariffs) {
if (tariff.effectiveFrom().isAfter(at)) {
break;
}
inForce = tariff;
}
return Optional.ofNullable(inForce);
}
public Set<String> operators() {
return Collections.unmodifiableSet(tariffsByOperator.keySet());
}
/** An operator's tariffs, oldest first. */
public List<Tariff> tariffs(String operator) {
return tariffsByOperator.getOrDefault(operator, List.of());
}
public static final class Builder {
private final Map<String, List<Tariff>> tariffs = new HashMap<>();
/** Adds a tariff version for an operator. Versions may be added in any order. */
public Builder operator(String operator, Tariff tariff) {
if (operator == null || operator.isBlank()) {
throw new IllegalArgumentException("operator must not be blank");
}
Objects.requireNonNull(tariff, "tariff");
List<Tariff> versions = tariffs.computeIfAbsent(operator, key -> new ArrayList<>());
for (Tariff existing : versions) {
if (existing.effectiveFrom().equals(tariff.effectiveFrom())) {
throw new IllegalArgumentException(
operator + " already has a tariff effective from " + tariff.effectiveFrom());
}
if (existing.id().equals(tariff.id())) {
throw new IllegalArgumentException(operator + " already has a tariff with id " + tariff.id());
}
}
versions.add(tariff);
versions.sort(Comparator.comparing(Tariff::effectiveFrom));
return this;
}
public FareCatalogue build() {
if (tariffs.isEmpty()) {
throw new IllegalStateException("a catalogue needs at least one tariff");
}
return new FareCatalogue(tariffs);
}
}
}package dev.benzarti.fares;
import java.time.Instant;
import java.util.Objects;
/**
* One version of an operator's pricing: its fares and its rules, in force from a given instant.
*
* <p>Tariffs are never edited. A fare change is a new tariff with a later {@code effectiveFrom}, so a
* trip from last month always re-prices exactly as it did last month. Every trip records the ID of
* the tariff that priced it.
*
* @param id stable identifier, recorded on every trip it prices
* @param effectiveFrom first instant (inclusive) at which a tap on is priced with this tariff
* @param fares fares between stops
* @param incompleteTrip charge for a tap on with no tap off
*/
public record Tariff(String id, Instant effectiveFrom, FareTable fares, IncompleteTripPolicy incompleteTrip) {
public Tariff {
if (id == null || id.isBlank()) {
throw new IllegalArgumentException("tariff id must not be blank");
}
Objects.requireNonNull(effectiveFrom, "effectiveFrom");
Objects.requireNonNull(fares, "fares");
Objects.requireNonNull(incompleteTrip, "incompleteTrip");
}
/** A tariff using the exercise's incomplete-trip rule. */
public Tariff(String id, Instant effectiveFrom, FareTable fares) {
this(id, effectiveFrom, fares, IncompleteTripPolicy.maxFareFromStop());
}
}package dev.benzarti.fares;
import java.math.BigDecimal;
import java.util.Objects;
/**
* What a passenger is charged when they tap on and never tap off.
*
* <p>The exercise's rule is {@link #maxFareFromStop()}. Operators differ here (some charge the
* maximum fare, some a flat penalty), so the rule is part of each operator's {@link Tariff} rather
* than being baked into the pricer.
*/
@FunctionalInterface
public interface IncompleteTripPolicy {
BigDecimal charge(String fromStop, FareTable fares);
/** Charge the highest fare possible from the stop: the exercise's rule. */
static IncompleteTripPolicy maxFareFromStop() {
return (fromStop, fares) -> fares.maxFareFrom(fromStop);
}
/** Charge the same amount wherever the passenger tapped on. */
static IncompleteTripPolicy flat(String amount) {
BigDecimal charge = Money.amount(Objects.requireNonNull(amount, "amount"));
return (fromStop, fares) -> charge;
}
}package dev.benzarti.fares;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Fares between pairs of stops. A fare applies in both directions.
*
* <p>The table is passed into the pricer rather than hard-coded, because every operator has its own
* stops and fares and those fares change over time. The highest fare from each stop, which is what
* an incomplete trip is charged, is derived from the table instead of being configured separately,
* so the two can never disagree.
*/
public final class FareTable {
private final Map<StopPair, BigDecimal> fares;
private final Map<String, BigDecimal> maxFareFrom;
private FareTable(Map<StopPair, BigDecimal> fares) {
this.fares = Map.copyOf(fares);
Map<String, BigDecimal> max = new HashMap<>();
fares.forEach((pair, fare) -> {
max.merge(pair.a(), fare, BigDecimal::max);
max.merge(pair.b(), fare, BigDecimal::max);
});
this.maxFareFrom = Map.copyOf(max);
}
public static Builder builder() {
return new Builder();
}
/** The fare table given in the exercise. */
public static FareTable sample() {
return builder()
.fare("Stop1", "Stop2", "3.25")
.fare("Stop2", "Stop3", "5.50")
.fare("Stop1", "Stop3", "7.30")
.build();
}
/** Fare between two different stops, in either direction. */
public BigDecimal fareBetween(String from, String to) {
if (from.equals(to)) {
throw new IllegalArgumentException("a fare needs two different stops, got " + from + " twice");
}
BigDecimal fare = fares.get(StopPair.of(from, to));
if (fare == null) {
throw new IllegalArgumentException("no fare between " + from + " and " + to);
}
return fare;
}
/** The most a passenger could have travelled from {@code stop}: what an incomplete trip costs. */
public BigDecimal maxFareFrom(String stop) {
BigDecimal fare = maxFareFrom.get(stop);
if (fare == null) {
throw new IllegalArgumentException("unknown stop " + stop);
}
return fare;
}
public boolean knowsStop(String stop) {
return maxFareFrom.containsKey(stop);
}
public Set<String> stops() {
return Collections.unmodifiableSet(maxFareFrom.keySet());
}
public static final class Builder {
private final Map<StopPair, BigDecimal> fares = new HashMap<>();
public Builder fare(String stopA, String stopB, String amount) {
Objects.requireNonNull(stopA, "stopA");
Objects.requireNonNull(stopB, "stopB");
if (stopA.equals(stopB)) {
throw new IllegalArgumentException("a fare needs two different stops, got " + stopA + " twice");
}
StopPair pair = StopPair.of(stopA, stopB);
if (fares.putIfAbsent(pair, Money.amount(amount)) != null) {
throw new IllegalArgumentException("fare between " + stopA + " and " + stopB + " defined twice");
}
return this;
}
public FareTable build() {
if (fares.isEmpty()) {
throw new IllegalStateException("a fare table needs at least one fare");
}
return new FareTable(fares);
}
}
/** An unordered pair of stops, so that Stop1→Stop2 and Stop2→Stop1 share one fare. */
private record StopPair(String a, String b) {
static StopPair of(String x, String y) {
return x.compareTo(y) <= 0 ? new StopPair(x, y) : new StopPair(y, x);
}
}
}package dev.benzarti.fares;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.Optional;
/**
* A priced trip built from a tap on and, when there is one, its tap off.
*
* <p>An incomplete trip has no tap off, so {@code finished} and {@code toStopId} are {@code null}
* and are exposed as {@link Optional}s. {@code tariffId} records which tariff version priced the
* trip, so any charge can be explained and reproduced later.
*/
public record Trip(
Instant started,
Instant finished,
String fromStopId,
String toStopId,
BigDecimal chargeAmount,
String companyId,
String busId,
Pan pan,
TripStatus status,
long tapOnId,
Long tapOffId,
String tariffId) {
static final DateTimeFormatter OUTPUT_FORMAT =
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss").withZone(ZoneOffset.UTC);
public Trip {
Objects.requireNonNull(started, "started");
Objects.requireNonNull(fromStopId, "fromStopId");
Objects.requireNonNull(chargeAmount, "chargeAmount");
Objects.requireNonNull(status, "status");
Objects.requireNonNull(pan, "pan");
Objects.requireNonNull(tariffId, "tariffId");
boolean hasTapOff = finished != null && toStopId != null && tapOffId != null;
if ((status == TripStatus.INCOMPLETE) == hasTapOff) {
throw new IllegalArgumentException(status + " trip with inconsistent tap off fields");
}
}
public Optional<Instant> finishedAt() {
return Optional.ofNullable(finished);
}
public Optional<String> destination() {
return Optional.ofNullable(toStopId);
}
/** Seconds between tap on and tap off; empty for an incomplete trip. */
public Optional<Long> durationSecs() {
return finishedAt().map(end -> Duration.between(started, end).getSeconds());
}
/**
* The trip in the exercise's output layout:
* {@code Started, Finished, DurationSecs, FromStopId, ToStopId, ChargeAmount, CompanyId, BusID, PAN, Status}.
* Fields an incomplete trip does not have are left empty.
*/
public String toCsvLine() {
return String.join(", ",
OUTPUT_FORMAT.format(started),
finishedAt().map(OUTPUT_FORMAT::format).orElse(""),
durationSecs().map(String::valueOf).orElse(""),
fromStopId,
destination().orElse(""),
Money.format(chargeAmount),
companyId,
busId,
pan.value(),
status.name());
}
}package dev.benzarti.fares;
import java.time.Instant;
import java.util.Objects;
/**
* A single tap event as reported by a reader on a bus.
*
* @param id unique identifier of the tap, assigned by the reader
* @param timestamp when the tap happened on the reader, in UTC
* @param type tap on or tap off
* @param stopId stop at which the tap happened
* @param companyId operator running the bus
* @param busId bus the reader is fitted to
* @param pan card that tapped
*/
public record Tap(long id, Instant timestamp, TapType type, String stopId, String companyId, String busId, Pan pan) {
public Tap {
Objects.requireNonNull(timestamp, "timestamp");
Objects.requireNonNull(type, "type");
requireText(stopId, "stopId");
requireText(companyId, "companyId");
requireText(busId, "busId");
Objects.requireNonNull(pan, "pan");
}
/** True when both taps were made on the same vehicle of the same operator. */
boolean sameVehicleAs(Tap other) {
return companyId.equals(other.companyId) && busId.equals(other.busId);
}
private static void requireText(String value, String name) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(name + " must not be blank");
}
}
}package dev.benzarti.fares;
import java.util.Objects;
/**
* A tap that could not be turned into a charge. It is reported rather than silently dropped, so an
* operator can see it and so it can be reprocessed if the missing information arrives later.
*/
public record Anomaly(Tap tap, Reason reason) {
public Anomaly {
Objects.requireNonNull(tap, "tap");
Objects.requireNonNull(reason, "reason");
}
public enum Reason {
/** A tap off with no open tap on for that card on the same bus. Not charged. */
TAP_OFF_WITHOUT_TAP_ON,
/** A second copy of a tap already received, with identical content. Ignored. */
DUPLICATE_TAP,
/** One of several taps sharing an ID but differing in content. No copy is trusted or charged. */
CONFLICTING_TAP_ID,
/** A tap at a stop missing from the tariff that applies, so it cannot be priced. */
UNKNOWN_STOP,
/** A tap at a known stop whose partner tap is at an unknown stop, so the trip cannot be priced. */
PAIRED_WITH_UNKNOWN_STOP,
/** A tap on for an operator with no tariff in force at that time. */
NO_TARIFF
}
}package dev.benzarti.fares;
import java.math.BigDecimal;
import java.math.RoundingMode;
/** Fare amounts are exact decimals with two places; floating point is never used for money. */
final class Money {
static final BigDecimal ZERO = amount("0.00");
private Money() {
}
static BigDecimal amount(String value) {
BigDecimal amount = new BigDecimal(value);
if (amount.signum() < 0) {
throw new IllegalArgumentException("amount must not be negative: " + value);
}
return amount.setScale(2, RoundingMode.UNNECESSARY);
}
static String format(BigDecimal amount) {
return "$" + amount.setScale(2, RoundingMode.UNNECESSARY).toPlainString();
}
}package dev.benzarti.fares;
import java.util.Objects;
/**
* Primary Account Number of the card that tapped.
*
* <p>The exercise asks for the PAN in the trip output so a card can be identified, so the full value
* is available through {@link #value()}. {@link #toString()} masks it, so a PAN never lands in a log
* line or an exception message by accident. In a production system this type would hold a token
* rather than the PAN itself (see {@code docs/DESIGN.md}).
*/
public record Pan(String value) {
public Pan {
Objects.requireNonNull(value, "pan");
if (!value.matches("\\d{12,19}")) {
throw new IllegalArgumentException("PAN must be 12 to 19 digits");
}
}
/** First six and last four digits, the rest masked: {@code 550000******5559}. */
public String masked() {
return value.substring(0, 6) + "*".repeat(value.length() - 10) + value.substring(value.length() - 4);
}
@Override
public String toString() {
return masked();
}
}package dev.benzarti.fares;
import java.math.BigDecimal;
import java.util.List;
/** Priced trips plus every tap that did not become part of a trip, and why. */
public record PricingResult(List<Trip> trips, List<Anomaly> anomalies) {
public PricingResult {
trips = List.copyOf(trips);
anomalies = List.copyOf(anomalies);
}
/** Sum of every charge, useful as a quick reconciliation figure. */
public BigDecimal totalCharged() {
return trips.stream().map(Trip::chargeAmount).reduce(Money.ZERO, BigDecimal::add);
}
}package dev.benzarti.fares;
/** Direction of a tap on a bus reader. */
public enum TapType {
ON,
OFF
}package dev.benzarti.fares;
/** Outcome of a trip, which decides how it is charged. */
public enum TripStatus {
/** Tapped on and off at different stops: charged the fare between them. */
COMPLETED,
/** Tapped on and off at the same stop: nothing is charged. */
CANCELLED,
/** Tapped on with no matching tap off: charged the highest fare possible from the stop. */
INCOMPLETE
}