Maybe D was wrong on contracts

Quirin Schroll qs.il.paperinik at gmail.com
Wed Sep 16 10:28:08 UTC 2026


On Tuesday, 8 September 2026 at 22:51:10 UTC, H. S. Teoh wrote:
> On Tue, Sep 08, 2026 at 10:23:37PM +0000, Quirin Schroll via 
> Digitalmars-d wrote: [...]
>> There might be a case for deprecating contract blocks entirely 
>> in favor of contract statements, i.e. no more `in { 
>> doWhatEverIWant(); }`, only `in(Expression)` because the 
>> `Expression` must return a `bool` (or be convertible to one). 
>> Then, `Expression == false` is a contract violation, 
>> `Expression == true` is success. A thrown `Exception` should 
>> be “promoted” to an `AssertError`, and a thrown `Error` 
>> shouldn’t be touched. If a contract is more complex than a 
>> series of `in`/`out`/`invariant` expressions, a private 
>> function that returns a `bool` is probably more readable 
>> anyway; an immediately invoked lambda is also possible.
> [...]
>
> That, or deprecate contracts that assert, and have them return 
> a `bool` instead.

If contract blocks just return `bool`, you can’t have an error 
message anymore, which is really a loss.

An improvement would be returning a `const(char)[]` for an error 
message, where `null` means no error. (It would also be easier to 
remember what means what, i.e. with returning a `bool`, there’ll 
be people who’ll mix up what `true` and `false` mean in that 
context.)

However, I’d still prefer `in(isGood(input), "input bad")`.

> Having contracts return `bool` instead of asserting gives the 
> compiler a way to emit logic to handle things like covariant / 
> contravariant handling in class hierarchies that doesn't 
> involve evil hacks around the semantics of `assert` and 
> catching `AssertError`'s (and dabbling with what's technically 
> UB per language spec).

The compiler can lower `assert`s that are lexically in the block 
to `bool`s. And it’s not UB in any shape or form if the compiler 
does it internally.


More information about the Digitalmars-d mailing list