Comparing Exceptions and Errors

kdevel kdevel at vogtner.de
Sun Jun 5 15:07:13 UTC 2022


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]. I would refactor the code:

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!
     // ...

   }
}

void main() {
   auto s = S();
   s.add(42);
   s.foo();
   s.a ~= 1; // does not compile
   s.foo();
}
```
[1] <https://www.google.de/search?q=incidental+data+structures>


More information about the Digitalmars-d-learn mailing list