Is it better to return null or empty collection?

前端 未结 18 1919
我在风中等你
我在风中等你 2020-11-22 07:56

That\'s kind of a general question (but I\'m using C#), what\'s the best way (best practice), do you return null or empty collection for a method that has a collection as a

18条回答
  •  情深已故
    2020-11-22 08:38

    Depends on your contract and your concrete case. Generally it's best to return empty collections, but sometimes (rarely):

    • null might mean something more specific;
    • your API (contract) might force you to return null.

    Some concrete examples:

    • an UI component (from a library out of your control), might be rendering an empty table if an empty collection is passed, or no table at all, if null is passed.
    • in a Object-to-XML (JSON/whatever), where null would mean the element is missing, while an empty collection would render a redundant (and possibly incorrect)
    • you are using or implementing an API which explicitly states that null should be returned/passed

提交回复
热议问题