Skip to content

Compare with a reference

Fast code is often clever code: a binary search, a cache, a hand-tuned parser. Clever code is where the off-by-ones live, and it’s hard to say what the right answer is for an input you didn’t think of. If there’s a simple way to get the same answer, even a slow one, let it say. Compare the two on every input.

A sorted list is searched by halving the range to look in, each time:

Search.java
/**
* Whether {@code sorted} holds {@code target}, halving the range it
* looks in each time.
*/
static boolean contains(List<Integer> sorted, int target) {
int low = 0;
int high = sorted.size() - 1;
while (low < high) {
int middle = (low + high) >>> 1;
int value = sorted.get(middle);
if (value == target) {
return true;
}
if (value < target) {
low = middle + 1;
} else {
high = middle - 1;
}
}
return false;
}

List.contains looks at every element in turn. It’s slow on a long list, and it’s obviously right. That makes it the reference:

ReferenceTest.java
@Test
void binarySearchAgreesWithAScan() {
forAll(sortedLists(), digits())
.check(
(sorted, target) -> {
boolean expected = sorted.contains(target);
assertEquals(expected, Search.contains(sorted, target));
});
}
static Domain<List<Integer>> sortedLists() {
return lists(digits()).map(values -> values.stream().sorted().toList());
}
static Domain<Integer> digits() {
return integers().atLeast(0).atMost(9);
}

The lists hold digits, 0 to 9, and so does the target. With so few values, the target is often in the list, often at one end, and often there more than once.

Terminal window
expected: <true> but was: <false>
binarySearchAgreesWithAScan failed after 7 tries (seed 0xae5f9e93dfe082a7)
shrunk counterexample: sorted = [0], target = 0
pin it: .example(/* sorted */ List.of(0), /* target */ 0)
rerun: PROPTASTIC_SEED=0xae5f9e93dfe082a7 ./gradlew test --tests 'ReferenceTest.binarySearchAgreesWithAScan'

A list of one, holding the target, and the search says it isn’t there. With one element, low and high are both 0, so low < high is false and the loop never looks. The loop should run while low <= high. The same mistake skips the last place left to look in any list, so a search misses values it narrows down to, not just in lists of one.

  • you’ve made something faster, and the old way still exists: an optimised algorithm, a cache in front of a slow call, a rewrite;
  • a library already does the job, and you can’t use it in production but can in a test: the JDK’s Collections.sort, java.time, a database;
  • a simple model of the system is easy to write: a HashMap standing in for a key-value store, a list standing in for a queue.
  • A bug the reference shares. If both were written from the same wrong idea, they agree. Keep the reference as plain as you can, so it’s right by reading it.
  • Differences the reference doesn’t decide. Asked for the index of a value that appears twice, a binary search and a scan can give different, equally right, answers. Compare what both promise: here, whether the value is there.

A reference that’s a few lines beside the code, run after every call rather than once, is a model: Follow a model checks a batching counter against i = i + 1 after each step, and Follow a model in the guides runs a model as a program of its own, in any language.

The reference is a test oracle: something that decides what the right output is. Comparing two implementations on the same inputs is also called differential testing, and when the reference is a simple model of the code, model-based testing. See Barr et al., 2015 on oracles, and Hughes, 2020 on model-based properties, in further reading.

Privacy