Skip to Content
Beautiful Code
book

Beautiful Code

by Andy Oram, Greg Wilson
June 2007
Intermediate to advanced
618 pages
18h 15m
English
O'Reilly Media, Inc.
Content preview from Beautiful Code

Chapter 7. Beautiful Tests

Alberto Savoia

Most programmers have had the experience of looking at a piece of code and thinking it was not only functional but also beautiful. Code is typically considered beautiful if it does what it’s supposed to do with unique elegance and economy.

But what about the tests for that beautiful code—especially the kind of tests that developers write, or should write, while they are working on the code? In this chapter, I am going to focus on tests, because tests can be beautiful themselves. More importantly, they can play a key role in helping you create more beautiful code.

As we will see, a combination of things makes tests beautiful. Unlike code, I can’t bring myself to consider any single test beautiful—at least not in the same way I can look at, say, a sorting routine and call it beautiful. The reason is that testing, by its very nature, is a combinatorial and exploratory problem. Every if statement in the code requires at least two tests (one test for when the condition evaluates to true and one when it evaluates to false). An if statement with multiple conditions, such as:

	if ( a || b || c )

could require, in theory, up to eight tests—one for each possible combination of the values of a, b, and c. Throw in control loops, multiple input parameters, dependencies on external code, different hardware and software platforms, etc., and the number and types of tests needed increases considerably.

Any nontrivial code, beautiful or not, needs not one, but ...

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

Good Code, Bad Code

Good Code, Bad Code

Tom Long
The Art of Clean Code

The Art of Clean Code

Christian Mayer
Strange Code

Strange Code

Ronald T. Kneusel
Five Lines of Code

Five Lines of Code

Christian Clausen

Publisher Resources

ISBN: 9780596510046Supplemental ContentErrata Page