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)
{
....
}
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.
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.
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.
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.
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).
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()) ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With