[OT] my experience with nullable types (C#)
Dadoum
dadoum at protonmail.com
Sat May 3 22:42:55 UTC 2025
On Wednesday, 30 April 2025 at 07:17:37 UTC, Kagamin wrote:
> Finally I had my chance to cope with nullable types in one of
> our C# codebases, and the experience wasn't nice.
>
> I had a prejudice that nullable types give some kind of promise
> that you will have only a few of them, but now that I think
> about it I can't remember anyone making this promise, and
> reality is quick to shatter this prejudice in a very ugly way.
> If you have a nullable type, all code now sees it as nullable,
> and you must insert null checks everywhere, even if you know
> it's not null by that point, and the volume of this null check
> spam is uncomfortably large.
I don't really understand, why is your type nullable if you know
for sure it's not null at this point ? If it's a function
parameter, you'll have to think and ask yourself: "Does my
function have any point on a null object?" If not, just remove
the nullable type there.
If your type has a nullable field, ask yourself: "When will this
be null?" If you know that after some action this can no longer
be null, just create a new type to encode this knowledge. Just
keep in mind that basically, having a nullable field means that
the object is in valid state even when the field is null. An
example of bad design is when a lot of functions dealing with
that object type have guards/asserts at the beginning. It means
probably that the object doesn't provide enough guarantees about
what it's storing.
More information about the Digitalmars-d
mailing list