Comparing Exceptions and Errors
Ali Çehreli
acehreli at yahoo.com
Sun Jun 5 17:04:49 UTC 2022
On 6/5/22 08:07, kdevel wrote:
> On Sunday, 5 June 2022 at 14:24:39 UTC, Ali Çehreli wrote:
> [...]
>> struct S {
>> int[] a;
>> int[] b;
>>
>> void add(int i) { // <-- Both arrays always same size
>> a ~= i;
>> b ~= i * 10;
>> }
>>
>> void foo() {
>> assert(a.length == b.length); // <-- Invariant check
>> // ...
>> }
>> }
>>
>> void main() {
>> auto s = S();
>> s.add(42);
>> s.foo();
>> }
>>
>> The code is written in a way that both arrays will *always* have equal
>> number of elements.
>
> I think this is what Sean Parent called "incidental data structure" [1].
Like many other programmers who include me, Sean Parent may be right.[1]
Other than being a trivial example to make a point, the code I've shown
may be taking advantage of the "structure of array" optimization. I am
sure Sean Parent knows that as well.
> I would refactor the code:
Most likely me too.
> struct T {
> int a;
> int b;
> }
>
> struct S {
> T [] t;
>
> void add(int i) {
> t ~= T (i, i * 10);
> }
>
> void foo() {
> // Look Ma no assert!
The assert may have been moved to another place:
struct T {
int a;
int b;
invariant() {
// Look Pa it's still here!
assert(b == a * 10);
}
}
Ali
[1] I stopped following Sean Parent when he dismissed D and me by waving
his hand behind and walking away: "A language with reference types? No,
thanks." That happened at the end of one of his presentations here at
the Silicon Valley C++, which I happened to co-host. I am sure he is
observant enough to one day realize that C++ has reference types by
convention. (I recently posted links to C++ core guidelines proving that
point of mine, one of which is something to the effect of "never pass
polymorphic types by-value".)
More information about the Digitalmars-d-learn
mailing list