Spec#, nullables and more
bearophile
bearophileHUGS at lycos.com
Sat Nov 6 14:15:31 PDT 2010
Walter:
> I don't see that non-null is such a special case that it would benefit from a
> special case syntax.
Well, nonnull are a special cases because:
- There is a good enough way to solve this problem. This is not true in the general case.
- null exceptions are very common bugs, among the most common ones in Java and C#.
> For example:
>
> NonNull!T p;
>
> v.s.
>
> nonnull T p;
>
> or worse:
>
> @nonnull T p;
The syntax I have proposed is:
T@ p;
> The compiler wouldn't do it. It would be a user supplied filter for a user
> defined subtype.
> ...
> The issue of null is only a small part of the possible space of subtyping checks
> one can find desirable in a program.
Are you using enough OOP in your programs? In OOP programs you manage object references all the time, so finding a null where you expect an object is common enough.
The idea of "a user supplied filter for a user defined subtype" looks nice, but in practice has problems because:
- It faces a general problem, while the most common problem in OOP code is much more restricted (presence of nulls).
- It doesn't allow a short light syntax like the @ and ? suffixes as I have proposed.
- And third, and most importantly, the compiler can't perform the second part of enforcement I was talking about. If we limit ourselves to just nulls, you may use many ways to tell the compiler that a specific reference can't be null:
If (x == null) {
// in this branch you do something
} else {
// in this branch the compiler assumes x is a nonnull type!
}
Or you may add an explicit assert:
// some code...
assert(x != null);
// here the compiler seex x as a nonnullable type
// more code...
Or even a cast, that performs a run-time test:
(cast(@)x).someMethod();
Where cast(@)x is syntax sugar for cast(typepof(x)@)x.
I don't know if you may use those three ways if you try to generalize the enforcement of a generic predicate attached to a type (there is a name for such types, we aren't inventing anything in this thread).
Bye,
bearophile
More information about the Digitalmars-d
mailing list