Open question: what code pattern you use usually for null safety problem
ddcovery
antoniocabreraperez at gmail.com
Fri Jan 15 00:52:09 UTC 2021
On Thursday, 14 January 2021 at 20:35:49 UTC, Dennis wrote:
> 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.
I agree: using null safety is a sign of something wrong in the
design (the need of dealing with nulls)... but if eventually you
need it, simple **if** or **&&** should be enough.
Curiously, languages like Dart (and its flutter framework)
performs extensive use of null safety (null is everywhere!!!) and
it seems that every "modern" language must deal with it.
Any case, I'm learning a lot: thank you Dennis for sharing!!!
More information about the Digitalmars-d-learn
mailing list