← Back to context

Comment by deepsun

4 days ago

Interestingly, Java had exactly that in mind when introduced `assert` keyword in very early versions (2002). It's equivalent to an `if` that can throw a runtime AssertionException, but only if the program is launched with `-enableassertions` flag.

The idea is that you use `-enableassertions` only during development, and your program should never rely on it. But it helps IDEs and static analyzers to have a contract about code.

D has a keyword prefix `debug`. So, one can write things like:

    ...
    debug if (x) printf("x: %d\n", x);
    ...

So, you can throw the -debug switch on the compiler and the debug code is enabled. For asserts,

    debug assert(lookMa);

and the check is only run when the -debug switch is done. It works remarkably well.

Another interesting property of `debug` is it turns off the safety checks in the target statement that follows it. Because, sometimes you just gotta do some unsafe tricks to figure out where your code went wrong.

As does .NET, with Debug class and related annotations.

.NET had DbC support for a while, but it was a Visual Studio Enterprise product, based on rewriting MSIL, and eventually was killed, as I imagine very few people bothered using contracts when such a license was required.

JVM languages like Clojure, Scala and Kotlin have DbC constructs beyond only assert.