Home > Backend Development > C++ > Should Methods Return Null or Empty Collections?

Should Methods Return Null or Empty Collections?

Linda Hamilton
Release: 2025-01-25 15:01:09
Original
286 people have browsed it

Should Methods Return Null or Empty Collections?

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>
Copy after login

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>
Copy after login

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>
Copy after login
() Method for this purpose:

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template