How do I create a Null Object in C#

后端 未结 5 1488
南笙
南笙 2020-12-16 00:07

Martin Fowler\'s Refactoring discusses creating Null Objects to avoid lots of

if (myObject == null)

tests. What is the right way to do th

5条回答
  •  感动是毒
    2020-12-16 00:44

    I'd like to mention here some interesting detail. Look at your class. Does it has any logic in it? This is not a class in its sense, this is a data structure. What you are trying to do is apply null object pattern to something it is not applicable to. Data structures is closer to value types, than to classes. There fore null check can be right in place to solve your problem. Null object pattern is not something you should always follow. Null object pattern is a thing you can use to avoid Liskov's substitution principle violation, to represent a class that does nothing, because null is not appropriate substitution for a class as it is a value, but not a class. But things are different with value types and data structures. Null is value! So in this case null check is the right thing to do.

提交回复
热议问题