Object.toString, toHash, opCmp, opEquals
Timon Gehr
timon.gehr at gmx.ch
Thu Apr 25 23:36:18 UTC 2024
On 4/26/24 01:06, Walter Bright wrote:
> The prototypes are:
>
> ```
> string toString();
> size_t toHash() @trusted nothrow;
> int opCmp(Object o);
> bool opEquals(Object o);
> ```
> ...
Beautiful. If I could change anything, I would remove `@trusted nothrow`
from `toHash`. Or just delete all the functions.
> which long predated `const`. The trouble is, they should be:
>
> ```
> string toString() const;
> size_t toHash() const @trusted nothrow;
> int opCmp(const Object o) const;
> bool opEquals(const Object o) const;
> ```
> ...
No, please.
> Without the `const` annotations, the functions are not usable by `const`
> objects without doing an unsafe cast. This impairs anyone wanting to
> write const-correct code,
"const correctness" does not work in D because const
a) provides actual guarantees
b) is transitive
It is fundamentally incompatible with many common patters of
object-oriented and other state abstraction. It is not even compatible
with the range API. Uses of `const` are niche. `const` is nice when it
does work, but it's not something you can impose on all code,
particularly object-oriented code.
> and also impedes use of `@live` functions.
> ...
Perfect. I have no intention of using `@live` functions. I do not see
their utility. It would be good to reuse the dataflow analysis you
implemented for `@live` in some productive way though.
> I recommend that everyone who has overloads of these functions, alter
> them to have the `const` signatures. This will future-proof them against
> any changes to Object's signatures.
I will not do that, because if it does not outright break my code (e.g.
because Phobos cannot support `const` ranges), it actually limits my
options in the future in a way that is entirely unnecessary.
This is a non-starter. We need another solution.
More information about the Digitalmars-d
mailing list