null and type safety
bearophile
bearophileHUGS at lycos.com
Wed Nov 5 05:16:59 PST 2008
Michel Fortin:
> Basically, if you declare some pointer to be restricted to not-null in
> a function signature, and then try to call the function by passing it a
> possibly null pointer, the compiler can tell you that you need to check
> for null at the call site before calling the function.
>
> It then ensue that when given a non-nullable pointer you can call a
> function requiring a non-nullable pointer directly without any check
> for null, because you know the pointer you recieved can't be null.
>
> Currently, you can acheive this with proper documentation of functions
> saying whether arguments accept null and if return values can return
> null, and write your code with those assumptions in mind. Most often
> than not however there is no such documentation and you find yourself
> checking for null a lot more than necessary. If this property about
> pointers in function parameters and return values were known to the
> compiler, the compiler could check for you that you're doing things
> correctly, warn you whenever you're forgetting a null check, and
> optimise away checks for null on these pointers.
The same is true making integral values become range values. If I want to write a function that takes an iterable of results of throwing a dice, I can use an enum, or control every item of the iterable for being in range 1 - 6. If range values are available I can just:
StatsResults stats(Dice[] throwing_results) { ...
Where Dice is:
typedef int:1..7 Dice;
I then don't need to remember to control items for being in 1-6 inside stats(), and the control is pushed up, toward the place where that throwing_results was created (or where it comes from disk, user input, etc). This avoids some bugs and reduces some code.
Bye,
bearophile
More information about the Digitalmars-d
mailing list