Open question: what code pattern you use usually for null safety problem

Dennis dkorpel at gmail.com
Thu Jan 14 20:35:49 UTC 2021


On Thursday, 14 January 2021 at 18:24:44 UTC, ddcovery wrote:
> If it's not a bother, I'd like to know how you usually approach 
> it

Usually I don't deal with null because my functions get primitive 
types, slices, or structs. `ref` parameters can be used to 
replace pointers that may not be null.
When something is nullable by design, I usually do this:

```
if (!person) {
     return; // early return if possible
}
if (auto f0 = person.father) {
     if (auto f1 = f0.father) {
        if (f1.name == "Peter") {
            doSomething();
        }
     }
}
```

It doesn't matter whether you're working with a class, pointer, 
or struct with opCast, this works. When access patterns get 
complex the nesting may get very deep.
Only if you can't avoid this I would consider using fancy helper 
functions, otherwise just use an if-statement or the && operator.


More information about the Digitalmars-d-learn mailing list