The case for strict parameter types

While refactoring a bit the way some “special” functions were handled in DWScript, I came about a case where the compiler started accepting strings as Math functions parameters.

While this comes naturally as an “interesting” side-effects of automatic typecasts, it left a feeling of “wrongness”, accepting literal code like Abs(“foo”) and then failing at run-time is asking for trouble.

Hence the introduction of an experimental strict type qualifier for function parameters, which will forbid automatic typecasts. This means you can now write code like

function OnlyFloats(f : type Float) : Float;

The extra “type” before the parameter denotes a strict type check with forbidden automatic typecasts, so OnlyFloats() will no longer accept Integer parameters (no automatic casts).

In the case of overloaded functions, this can be used to have Integer, Float and Variant overloads, without the Variant overload resulting in String being accepted through automatic boxing:

function OnlyNumerics(f : type Float) : Float; overload;
function OnlyNumerics(f : type Integer) : Integer; overload;
function OnlyNumerics(f : type Variant) : Variant; overload;

The idea here being to deter problematic (mis)uses of a function or method by providing more compile-time control.

Note that when used with parameters of a class type, sub-classes of that class will still be accepted (as there is no typecasting in that case, only a type check).

Note that this feature is still experimental at the moment, and subject to change.

There is awlays an xkcd !

 

 

4 thoughts on “The case for strict parameter types

  1. History runs in circles. From strict type checking to automatic type casting now back to strict type checking again, just with some more complicated syntax. We could of course have simply kept it as it was and added syntactic sugar for automatic typecasting like:

    procedure TakeWhateverConvertsToANumber(Number: autocast double);

  2. Indeed it does 😁

    It is a game of sword and shield between code that has universal reach (like Math or String stuff) and types that want to encompass and hold everything, even when that makes no sense.

Leave a Reply

Your email address will not be published. Required fields are marked *