While perusing reddit, I came across this blog post and subsequent comments where people were debating whether or not you should return a null or an empty collection. The point is, it shouldn't matter. Any consuming code shouldn't make assumptions about what it's getting back from anther piece of code. Ever. If it could possibly be null, you check for null, even if you developed the other code and know it can't be null. Why? Because while you know it can't be null, the code, and the rest of the world, doesn't know that. So when you get hit by a bus and some other poor developer updates that GetCollection method to return null, he doesn't break anything that calls it, because everything that calls it is taking on it's own responsibility of making sure it has its ducks in a row.
No malloc is good malloc
Another small point to make here: Instantiating an empty collection just because you assume the other code isn't checking for nulls is simply wasting resources to accommodate bad practice elsewhere.
When writing a method to return something:
- Return whatever makes sense, not what you worry someone needs.
- You shouldn't be concerned with what the consuming code is doing. (That's not separation of concerns is it?)
- Do not abuse system resources to be "nice" for other developers.
When consuming a method that returns something:
- The code you're writing is responsible for checking to ensure what is received is valid before operating on it.
- If it can't be null, check for null.
- If it has to be within a certain range, check to make sure it's in a certain range.
- You get the idea. Assume nothing about the returned value.
TL;DR: You should probably be returning null, and when consuming code, you should always confirm returned values before using them.