Assumptions and Assertions

Every piece of code is built upon a platform of myriad assumptions—things that have to be true for it to behave as expected. More often than not, bugs arise because one or more of these assumptions are violated or turn out to be mistaken.

It’s impossible to avoid making such assumptions and pointless to try. But the good news is that not only can we verify that they hold, we can do so automatically with assertions.

What does an assertion look like? In Java, they can take two forms—the first, simpler form is as follows:

 
assert​ condition;

The second form includes a message that is displayed if the assertion fails:

 
assert​ condition : message;

Whichever form you use, whenever it’s executed, an assertion evaluates ...

Get Debug It! now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.