Rant: Date and Time fall short of simplicity in D

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 29 19:30:14 PDT 2013


On Fri, 29 Mar 2013 18:07:38 -0400, Jesse Phillips  
<Jessekphillips+D at gmail.com> wrote:

> On Friday, 29 March 2013 at 21:36:37 UTC, Steven Schveighoffer wrote:
>> (and yes, casts are dangerous and should be avoided).
>
> I think you are applying "common knowledge" to something where it  
> doesn't apply.
>
> auto foo = cast(TickDuration) bar;
>
> This is not unsafe, unless you claim that opCast is being implemented in  
> a dangerous manner (takes a Variant and converts it to 32)

Well, when you cast, you can inadvertently remove const, shared,  
immutable, etc.  In these cases, cast is safe, but refactoring can make  
things unsafe.  There are certain cases with cast where it happily  
discards const or immutable without so much as a peep.  Changing the type  
of bar above to const TickDuration, for example, could allow code that was  
not intended to discard const to do so.

In the case of TickDuration, it is a purely-value type, so it's not an  
issue.  But something with a reference could behave badly.  If you  
accidentally end up invoking the *compiler* cast, the type system goes out  
the window.

>
> I'm really confused on what your argument is. It sounds like you don't  
> want to!() to be able and convert user types, but if it does than it  
> shouldn't be allowed to use cast.

No, that's not what I'm saying.  I think the *mechanism* for 'to' to  
convert types should be something other than cast.  At least it should be  
allowed.

> I'm not sure what issue you are expecting to prevent by requiring  
> bar.toTickDuration() instead of using cast or to!().

I want to *allow* bar.toTickDuration(), and if you want to use  
to!TickDuration(), that should be fine too.  But to REQUIRE  
cast(TickDuration) or importing another module to access the API in a safe  
manner should not be considered good practice.  A cast should signal a  
red-flag for code reviews, it should not be a mundane API call.

-Steve


More information about the Digitalmars-d mailing list