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

ddcovery antoniocabreraperez at gmail.com
Thu Jan 14 22:08:41 UTC 2021


On Thursday, 14 January 2021 at 19:24:54 UTC, Adam D. Ruppe wrote:
> On Thursday, 14 January 2021 at 18:24:44 UTC, ddcovery wrote:
>> This is only an open question to know what code patterns you 
>> usually use to solve this situation in D:
>
> I'm almost never in this situation except for reading things 
> like xml or json data that may be missing.

Yes, this is the usual situation (Personally, I use "DTO" 
structured objects... that are serialized/unserialized to JSON)

>
> So I just special cased those. My json lib doesn't return null 
> per se, it returns var(null) which is allowed to just return 
> more harmless nulls. Thus you write 
> `person.father.father.name.get!string` and it will be empty if 
> anything was null in the chain.
>
> With dom, you can optionSelector("person > father > father > 
> name").innerText and again if the selector returned null, all 
> its methods also just return empty strings or whatever.

Selectors are a good option to navigate on dom/json, but on 
structured objects too.  The good think with "templates" in D is 
that this "path/selector" can be compiled internally to a 
map/filter combination completly "null" free... I was 
experimenting last days with this and I think that a functional 
orientation (using a MayBe monad implemented as Range ) is the 
best way to begin.

>
> So the library handles these special cases and then I don't 
> worry about nested nulls anywhere else since I consider it bad 
> style to even be in that situation in the first place.

I agree: it is a bad style. Personally I allways use MayBe monads 
in my "DTO"s (that is the effect of having worked with scala :-).

The only "cons" with Nullable!T (the "standard" D MayBe 
equivalent) is that it is not "compatible" with Range libraries 
(it is not a Range:  you use "apply" instead "map", you have not 
"filter", you can't "chain" a range and Nullable, you can't 
"join" a range of Nullables like a Range of ranges).  This is the 
reason I'm "experimenting" with my own "MayBe" InputRange that 
can be created in the form of "Some" or "None" (it's inmutable 
contrary to what happens with Nullable) and is compatible with 
all std.algorithm (and array) library.






More information about the Digitalmars-d-learn mailing list