Hacker News new | ask | show | jobs
by joshka 575 days ago
I think we're really talking past each other at this point, so I'm probably not going to respond more on this. Maybe in C++ where you don't have better techniques available, then assertions *are* the best tool you can reach for for this sort of thing. In many other languages however we do have better options. These should chosen over using assertions when possible as the outcome is significantly better.

> For example going out of bounds on an array, what are your options? Pretend nothing is wrong, return a default value, throw an exception?

The article is talking about assertions in rust. The answer to that question in rust is to use `.get()` which returns `Option<T>`. This moves the condition where the array index is outside the bounds into a structured result rather than causing an application crash. An assertion that crashes the program would be useless there, as the language makes the type of error one that is idiomatically avoided. This (in addition to testing) is part of my point. Dig deep into the implementation of this in the std lib and there's no assertion, just a bounds check which either returns `Some(value)` or `None`.

The part I'm saying is problematic is not the check part of the assertion, it's the crashing part. Write software that avoids needing to crash by proving that the scenarios where invariants not invalid don't exist. When you do that any assertions which you include are code paths which are impossible to ever hit. This is by definition.

Expanding on the article example, it requires that the `youngest` variable is always >= 0. Just define that as `u8` and let the compiler be your check. You never need an assertion to test a tautology.