Return to NULL or empty collection: the best practice
When the design returns the set as a method of returning the value type, it will cause a problem: Should it return null or an empty collection? The best practice is strongly recommended to return the empty collection in all circumstances.
Why choose an empty collection?
Returning NULL is a bad practice because it can cause unnecessary code complexity and potential runtime errors. For example, if you return null for the collection attribute:
If myInstance.CollectionProperty is indeed null, this code may cause abnormalities. On the contrary, it is best to return an empty collection to ensure that the above code can still be executed without mistakes.The best practice of attributes
<code class="language-c#">if(myInstance.CollectionProperty != null) { foreach(var item in myInstance.CollectionProperty) /* 如果 CollectionProperty 为 null,此代码可能会失败 */ }</code>
For the attributes of the return set, it is recommended to initialize the attribute only once. This can be completed during the constructor that contains the classes containing the attribute:
Use C# 6, you can use a more concise version:
The best practice of method
<code class="language-c#">public List<foo> Foos { public get; private set; } public Bar() { Foos = new List<foo>(); }</code>
For the method of returning the set, if the actual set does not exist, the empty collection is returned. You can use EnuMerable.empty
<code class="language-c#">public List<foo> Foos { get; } = new List<foo>();</code>
This method ensures that even if InnergetFoos () returns NULL, this method will still return an empty set to prevent potential errors.
The above is the detailed content of Should Methods Return Null or Empty Collections?. For more information, please follow other related articles on the PHP Chinese website!