Chapter 94. Write Small Functions Using Examples

Keith Braithwaite

image with no caption

WE WOULD LIKE TO WRITE CODE THAT IS CORRECT, and have evidence on hand that it is correct. It can help with both issues to think about the “size” of a function. Not in the sense of the amount of code that implements a function—although that is interesting—but rather the size of the mathematical function that our code manifests.

For example, in the game of Go there is a condition called atari in which a player’s stones may be captured by her opponent: a stone with two or more free spaces adjacent to it (called liberties) is not in atari. It can be tricky to count how many liberties a stone has, but determining atari is easy if that is known. We might begin by writing a function like this:

boolean atari(int libertyCount)
    libertyCount < 2

This is larger than it looks. A mathematical function can be understood as a set, some subset of the Cartesian product of the sets that are its domain (here, int) and range (here, boolean). If those sets of values were the same size as in Java, then there would be 2L*(Integer.MAX_VALUE+(–1L*Integer.MIN_VALUE)+1L) or 8,589,934,592 members in the set intxboolean. Half of these are members of the subset that is our function, so to provide complete evidence that our function is correct, we would need to check around 4.3x109 examples.

This is the essence of the claim that tests cannot ...

Get 97 Things Every Programmer Should Know now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.