Asserting Implications

31 points by matklad


arxanas

One advantage of using an if statement is that you can often get better coverage information from a test harness than with a single boolean condition. Besides the universal assertion itself (“for all x meeting this condition…”), it’s likely that there’s an implicit existential assertion (“there exists some x that meets this condition…”). If the assertion condition is never triggered in tests. then you likely want to know that, since it could potentially mean that you have a gap in test coverage, or that there’s a stronger assertion that you actually want (“there are no x meeting this condition…”).

On the other hand, sometimes it’s fine if there’s no code path triggering that condition at present. It could protect against a future regression or redesign, or simply defensive programming.

peterbourgon
// Before:
assert(header_b != null or replica.commit_min == replica.op_checkpoint);

// After:
if (header_b == null) assert(replica.commit_min == replica.op_checkpoint);

It seems like the invariant being asserted here is that either header_b is null, or header_b is not null and replica.commit_min == replica.op_checkpoint. So for me that reads most clearly as

assert( (header_b == null) or (header_b != null and replica.commit_min == replica.op_checkpoint) );

YMMV!

valdemar

It should maybe be noted that it slightly changes the semantics if you have a short circuiting or implementation, though that is probably something that is a really good idea to not rely on.

Unrelated, it is nice to see a good old over-painting of a fresco instead of using some generative “AI” to make a header image.