Anything in D to avoid check for null everywhere?

ddcovery antoniocabreraperez at gmail.com
Wed Jan 13 09:02:37 UTC 2021


On Tuesday, 12 January 2021 at 21:37:11 UTC, Jack wrote:
> I was looking for a way to avoid null checks everywhere. I was 
> checking the Null object pattern, or use something like enforce 
> pattern, or even if I could make a new operator and implement 
> something like C#'s .? operator, that Java was going to have 
> one but they refused[1] (doesn't behave exactly as C#'s 
> actually), Kotlin also got something in this area[2]
>
> What some D ways to avoid those checks?
>
> [1]: 
> https://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000047.html
> [2]: 
> https://kotlinlang.org/docs/reference/null-safety.html#safe-calls

Personally, I really like functional orientation (MayBe, None, 
Some... and pattern matching) avoiding the use of null, but D is 
a "system" language compatible with C and null is mandatory.

Some months ago I wrote an utility template to simulate the ?. 
mechanism.


The resulting syntax:

   class Person
   {
     string name;
     Person father;

     this(string name, Person father){	
       this.name=name;
       this.father=father;
     }
   }

  Person p = new Person("Peter", new Person("John", null));
  assert( p.d!"father".d!"father".d!"name".get is null);
  assert( p.d!"father".d!"name".get == "John");
  assert( p.d!"father".d!"name".d!"length".get(0) == 4);
  assert( p.d!"father".d!"father".d!"name".d!"length".get(0) == 0);
  assert( (cast(Person) null).d!"father".d!"father".d!"father".get 
is null);


That is a "compact" version of a first solution using lambdas

  assert( 
dot(p).dot(a=>a.father).dot(a=>a.father).dot(a=>a.name).dot(a=>a.length).get(0) == 0);

Find more details here:

https://run.dlang.io/gist/392c06e745d1a35df71084ce4d29fed7



More information about the Digitalmars-d-learn mailing list