The problem with Nullable: nullable(null).isNull is false.

Steven Schveighoffer schveiguy at gmail.com
Mon Jul 25 13:05:08 UTC 2022


On 7/25/22 4:58 AM, Piotr Mitana wrote:
> Hello. As Nullable has gained a bit recently (disabling automatic 
> aliasing to content andrange interface – thanks for that!), it needs one 
> more improvement.
> 
> Currently:
> 
> ```d
> assert(nullable(null).isNull == false);
> ```
> 
> It's might be very misleading – to make it truly safe, an object in 
> nullable requires a double-check:
> 
> ```d
> class C {}
> 
> // ...
> 
> Nullable!C aThing = someCode()
> 
> if(!aThing.isNull && aThing.get != null) {
>      // Now we are safe
> }
> 
> ```
> 
> The simple solution is to use the `Nullable(T, nullValue)(T t)` variant, as
> 
> ```d
> assert(nullable!null(null).isNull == true);
> ```
> 
> The solution in my opinion is:
> 
> - disable `Nullable(T)` for any type that can have `null` value,
> - for `Nullable(T, T nullValue)` add default the `nullValue` to `null` 
> for these types, so that it replaces the `Nullable(T)` usage.

A counter example:

```d
Nullable!C getDBValue(int key);

auto x = getDBValue(42);
if(x.isNull) { writeln("database does not contain the requested row"); }
else if(x.get is null) { writeln("database contains the requested row, 
but the value is set to NULL"); }
```

The real "problem" is that Nullable is called "Nullable".

-Steve


More information about the Digitalmars-d mailing list