I agree with most posts here, which tend towards null
.
My reasoning is that generating an empty object with non-nullable properties may cause bugs. For example, an entity with an int ID
property would have an initial value of ID = 0
, which is an entirely valid value. Should that object, under some circumstance, get saved to database, it would be a bad thing.
For anything with an iterator I would always use the empty collection. Something like
foreach (var eachValue in collection ?? new List<Type>(0))
is code smell in my opinion. Collection properties shouldn't be null, ever.
An edge case is String
. Many people say, String.IsNullOrEmpty
isn't really necessary, but you cannot always distinguish between an empty string and null. Furthermore, some database systems (Oracle) won't distinguish between them at all (''
gets stored as DBNULL
), so you're forced to handle them equally. The reason for that is, most string values either come from user input or from external systems, while neither textboxes nor most exchange formats have different representations for ''
and null
. So even if the user wants to remove a value, he cannot do anything more than clearing the input control. Also the distinction of nullable and non-nullable nvarchar
database fields is more than questionable, if your DBMS is not oracle - a mandatory field that allows ''
is weird, your UI would never allow this, so your constraints do not map.
So the answer here, in my opinion is, handle them equally, always.
Concerning your question regarding exceptions and performance:
If you throw an exception which you cannot handle completely in your program logic, you have to abort, at some point, whatever your program is doing, and ask the user to redo whatever he just did. In that case, the performance penalty of a catch
is really the least of your worries - having to ask the user is the elephant in the room (which means re-rendering the whole UI, or sending some HTML through the internet). So if you don't follow the anti-pattern of "Program Flow with Exceptions", don't bother, just throw one if it makes sense. Even in borderline cases, such as "Validation Exception", performance is really not an issue, since you have to ask the user again, in any case.