Skip to Content
97 Things Every Programmer Should Know
book

97 Things Every Programmer Should Know

by Kevlin Henney
February 2010
Beginner
255 pages
6h 10m
English
O'Reilly Media, Inc.
Content preview from 97 Things Every Programmer Should Know

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 prove the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

40 Algorithms Every Programmer Should Know

40 Algorithms Every Programmer Should Know

Imran Ahmad
Five Lines of Code

Five Lines of Code

Christian Clausen

Publisher Resources

ISBN: 9780596809515Errata PageSupplemental Content