Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return empty List<T> or null when no list items present?

Tags:

c#

When I have a method which returns a collection of objects, what I should return if the objects count is zero? null or just empty List<T>? What is good practice?

public List<string> GetPupilsByClass(string className)
{
     ....
}
like image 791
Neir0 Avatar asked Aug 07 '11 07:08

Neir0


People also ask

Should you return null or empty list?

Empty collection. Always. It is considered a best practice to NEVER return null when returning a collection or enumerable. ALWAYS return an empty enumerable/collection.

Which method returns an empty list if there are no matches?

The findAll method returns an immutable IndexedSeq of all matching elements. If no elements match the query, findAll returns an empty IndexedSeq. It already returns an empty list if no elements are found, and will not cause an exception. The scala findAll method will do the same.

How do you check if a list is empty or null?

The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.

How do I check if a list is empty or null in Python?

In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.


3 Answers

I'd definitely return an empty list so methods can still be called on the object without requiring null checks. There's a difference between returning an empty list and returning nothing at all, so the calling code probably isn't expecting to receive a null reference anyway (unless an exception occurs or something).

like image 125
BoltClock Avatar answered Oct 21 '22 04:10

BoltClock


An empty list is what I'd expect as a caller. Null would indicate to me that the "conceptual list" is undefined, like null in a database.

Also, by always returning empty collections rather than null, clients like these will never fail:

foreach(var element in obj.Method()) ...
like image 31
Jörgen Sigvardsson Avatar answered Oct 21 '22 04:10

Jörgen Sigvardsson


It depends on a number of factors, but an empty list would be a more typical return value, as otherwise the caller must know to perform null checking. The main time I'd return a null is if it was a method of this style:

bool Try*(args, out result)

The caller expects (on receiving false) not to even look at the value of result.

If you happen to be returning arrays, there is a nice cheat - you can store a zero-length typed array in a static field somewhere are return that. But ultimately an empty list isn't going to be a huge overhead to allocate, so just sent that.

like image 26
Marc Gravell Avatar answered Oct 21 '22 04:10

Marc Gravell