On 7/12/21 5:42 PM, someone wrote:

> On Monday, 12 July 2021 at 23:25:13 UTC, Ali Çehreli wrote:
>> On 7/12/21 3:35 PM, someone wrote:
>>
>> >>> private size_t pintSequenceCurrent = cast(size_t) 0;
>> >
>> >> Style: There's no need for the casts (throughout).
>> >
>> > [...] besides, it won't hurt, and it helps me in many ways.
>>
>> I think you are doing it only for literal values but in general, casts
>> can be very cumbersome and harmful.
>
> Cumbersome and harmful ... could you explain ?

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

Harmful because it bypasses the compiler's type checking.

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

> 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;

Ali


Reply via email to