What's better for implementing null object pattern:
1) provide special state for instance
or
2) use everywhere ? (Nullable) operator?
And I'm thinking about structs only.
What's better for implementing null object pattern:
1) provide special state for instance
or
2) use everywhere ? (Nullable) operator?
And I'm thinking about structs only.
In general, you should avoid null
where possible.
If you really have an optional parameter/field, then it is ideomatic to make the instance nullable.
If you have a struct where null
means something special - something that is not "this instance does not exist" then it depends. If other parts of your code/api use null to mean this special thing, then just use null
. If not, then it may be better to make a specific instance of the struct mean that other value, or create your own Maybe Type.
As always, there's no single "better" for all situations. Program design is a matter of trade offs.
Use null
. It doesn't clutter your stuff up with a null instance, it doesn't fool people who think they have an instance into realizing they don't have an instance well after the bug occurred, and it's simply much easier codewise to be able to use the same rules for all nullable things.