Skip to content

Conservation

Money moved between accounts, items moved between warehouses, a bill split between friends: the amount shouldn’t change, only where it is. A rounding or an off-by-one loses a cent or makes one, and nobody notices until the books don’t balance. Conservation totals it before and after, and checks nothing was made or lost.

Friends split a restaurant bill. Each pays a share, in cents:

Bill.java
/** Each person's share of the bill, in cents. */
static List<Long> split(long totalInCents, int people) {
return Collections.nCopies(people, totalInCents / people);
}

However big the bill and however many people, the shares should add up to the bill:

ConservationTest.java
@Test
void splittingABillKeepsEveryCent() {
forAll(longs().atLeast(0).atMost(100_000), integers().atLeast(1).atMost(12))
.check(
(totalInCents, people) -> {
var shares = Bill.split(totalInCents, people);
long paid = shares.stream().mapToLong(Long::longValue).sum();
assertEquals(totalInCents, paid);
});
}
Terminal window
expected: <1> but was: <0>
splittingABillKeepsEveryCent failed after 1 try (seed 0x3a9b3a170143cbac)
shrunk counterexample: totalInCents = 1, people = 2
pin it: .example(/* totalInCents */ 1L, /* people */ 2)
rerun: PROPTASTIC_SEED=0x3a9b3a170143cbac ./gradlew test --tests 'ConservationTest.splittingABillKeepsEveryCent'

One cent between two people is no cent each, so the cent is lost. Any bill that doesn’t divide evenly loses what’s left over, less than a cent per person. A test that splits 1,000 cents between four passes. A fix gives the leftover cents, one each, to the first few people.

The shrunk counterexample is the smallest bill and the fewest people that lose a cent. With one person nothing can be lost, so two is as small as it gets.

  • something is moved, split or regrouped, and the total should stay put: money, stock, votes, the bytes in a stream, the elements of a list;
  • the code rounds, as money and percentages do;
  • you can’t say what each part should be, but you know what they add up to.
  • A total that’s right with the parts wrong. Giving one person the whole bill keeps every cent. Add a property for fairness: no two shares differ by more than a cent.
  • Losses that cancel out. A bug that loses a cent here and makes one there keeps the total. The bank page’s list of transfers checks the total once, at the end; check it after every step, as an invariant does, to see each step’s own mistake.

The name comes from physics, where a conservation law says a quantity, such as energy, is neither made nor destroyed. In testing it’s an invariant over a sum, and the classic example is money in a bank.

Privacy