Java like "assert" statement

Many people who object to assertions are misunderstanding their purpose. The whole point of an assertion is that you can remove it from production. If you want to leave it in production, there are other language elements that you can use to perform the same tests.

Assertions give you the freedom to write slower tests. This sounds strange to a lot of people, but my point is that I don’t have to worry about an inefficient test when I’m writing an assertion, since it won’t be in production. Steve Maguire, in his excellent book Writing Solid Code, gave a very good example from the early days of Microsoft Excel. To improve performance, they developed an algorithm to only calculate cells that would be effected by the recent changes, instead of slowly recalculating everything. But the algorithm had to work perfectly. So they put in an assertion that recalculated every cell, and tested to make sure the results were the same. Naturally, it ran very slowly when this was enabled, but they also caught every bug they needed to catch, so when they released their new app, this aspect worked perfectly. This illustrates the advantage of the “freedom to write slow tests.”

In short, assertions are for development-phase diagnostic tests. Some people ask, “if you don’t want them in production, why don’t you just remove them before your release?” Because you’ll want to put them back when you start working on version 2.

In Kotlin, I really want to see assertions that behave like in Java, where they are disabled by default but can be enabled at run time.

1 Like