-2

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.

3
  • 2
    Without context specified, this question is pointless. The nullable is not even a null object pattern.
    – tia
    Commented Mar 23, 2015 at 18:54
  • Welcome to monads - the choice of null representation depends on whether the operations you want to perform has a natural representation for null. Basically if it exists, it is better to use it. Otherwise, it means any code that wants to use the object has to explicitly check for null, which means your choice is narrowed down to one, and therefore your question will have an answer.
    – rwong
    Commented Mar 23, 2015 at 20:00
  • For example, if your operation is addition, use zero. If your operation is multiplication, use one. If your operation is logical-and, use true. If your operation is logical-or, use false. Etc. If you describe your use case in detail, someone might be able to give more specific suggestions.
    – rwong
    Commented Mar 23, 2015 at 20:02

2 Answers 2

1

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.

0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.