On Tuesday, 13 July 2021 at 05:26:56 UTC, Ali Çehreli wrote:

Cumbersome because one has to make sure existing casts are correct after changing a type.

ACK.

Harmful because it bypasses the compiler's type checking.

Hmmm ... I'll be reconsidering my cast usage approach then.

>> For example, if we change the parameter from 'int' to
'long', the cast
>> in the function body is a bug to be chased and fixed:
>>
>> // Used to be 'int arg'
>> void foo(long arg) {
>>   // ...
>>   auto a = cast(int)arg;  // BUG?
>>   // ...
>> }
>
> nope, I'll never do such a downcast

The point was, nobody did a downcast in that code. The original parameter was 'int' so cast(int) was "correct" initially. Then somebody charnged the parameter to "long" and the cast became potentially harmful.

ACK.

> UNLESS I previously tested with if
> () {} for proper int range; I use cast a lot, but this is
mainly because
> I am used to strongly-typed languages etc etc,

Hm. I am used to strongly-typed languages as well and that's exactly why I *avoid* casts as much as possible. :)

> for example if for
> whatever reason I have to:
>
> ushort a = 250;
> ubyte b = cast(ubyte) a;
>
> I'll do:
>
> ushort a = 250;
> ubyte b = cast(ubyte) 0; /// redundant of course; but we
don't have

We have a different way of looking at this. :) My first preference would be:

 ubyte b;

This alternative has less typing than your method and is easier to change the code because 'ubyte' appears only in one place. (DRY principle.)

  auto b = ubyte(0);

Another alternative:

  auto b = ubyte.init;

ACK. I'll be revisiting the whole matter. I just re-read your http://ddili.org/ders/d.en/cast.html chapter. I did not have a clear understanding between the difference of to!(...) and cast() for example; and, re-reading integer promotion and arithmetic conversions refreshed my knowledge at this point.

Ali


Reply via email to