Skip to content
Tech News
← Back to articles

You Must Fix Your Asserts (Zig)

read original get Zig Programming Language Book → more articles
Why This Matters

This article highlights the importance of properly handling assertions in programming, emphasizing that disabling asserts in production environments is a dangerous practice. Proper use of assertions can catch bugs early and improve code reliability, which is crucial for the tech industry and consumers relying on robust software. It advocates for fixing asserts rather than disabling them, ensuring safer and more maintainable codebases.

Key Takeaways

Fear is the killer of the mind ...and the codebase as well.

A user on a discussion platform wrote:

I think “disabling asserts in prod” is a pretty common technique, yeah?

As far as I know that is probably a correct statement, but I believe it to be an irredeemably bad practice. Let’s start with some context first, since this discussion started because of how std.debug.assert works in Zig.

Asserts in general

An assert is a line of code that introduces a new fact to the program, such as “this argument can never be null”, or “this integer can never be even”, and they kinda look like this:

assert ( my_arg != null ); assert ( my_num % 2 != 0 );

If your type system can be used to enforce one of these constraints, then you will probably want to use the facilities in your language rather than asserts.

For example, in Zig normal pointers (e.g. *Foo ) can never be null, while optional pointers ( ?*Foo ) can, but they also force you to check before you can access the value (and for which Zig has dedicated idioms).

Asserts can be used to explicitly state pre/post conditions and invariants in your code. This is useful because, if you pick good assertions, those will be able to protect you from programming mistakes better than unit tests, especially if you fuzz your code.

... continue reading