Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties of collection type

When the property have some collection type like

public IList<MyItemClass> MyList{ get; }

IMHO, it's better to return empty collection instead of null value.
There are many ways to implement such functionality.

public IList<MyItemClass> MyList{ get; private set; }
public MyClass(){
    MyList = new List<MyItemClass>();
}

This way allow to decrease number of class fields, but you need to put code in each constructor.

private List<MyItemClass> _myList = new List<MyItemClass>();
public IList<MyItemClass> MyList{ get{ return _myList; } }

This is standard way. But when somebody write something to your code he can use private field instead of property and you can get some bugs when you refactor get action.

private List<MyItemClass> _myList;
public IList<MyItemClass> MyList{ get{ return _myList??(_myList = new List<MyItemClass>()); } }

And this is the variant of the previous way with lazy loading.

What are you prefer to return as default value for collection? If this is empty collection how do you implement it?

like image 910
Steck Avatar asked Feb 19 '10 09:02

Steck


1 Answers

From the .NET Design Guidelines:

Do provide sensible default values for all properties, ensuring that the defaults do not result in a security hole or an extremely inefficient design.

Extending this principle and combining it with the Principle of Least Surprise should make it abundantly clear that you should always return an empty collection instead of null.

Why put the burden of checking for null on your caller when you can provide a sensible, intuitive default value?

The whole point of encapsulation is to do the work in a single place. It may make that specific class implementation a bit more complex, but it makes using its API simpler.

In most cases I implement the collection as an invariant in the containing type:

public class MyClass
{
    private readonly List<Foo> foos;

    public class MyClass()
    {
        this.foos = new List<Foo>();
    }
}

Notice the use of the readonly keyword which ensures that once set, the list can never be replace or nulled out (but it can still be reset). This protects the list as an invariant of the class, which safes me from writing null checks in the rest of my code.

Lazy loading is also a valid coding idiom, but I only use it when I explicitly need it.

like image 192
Mark Seemann Avatar answered Oct 05 '22 16:10

Mark Seemann