Everywhere I read constantly rehashes the idea of “never return nulls” but what should I return if not null in the cases where a value cannot be found?
Take the following method
List<Customer> GetCustomerListByRoleID(Guid RoleID) {}
In this case (and in most plural methods) its easy to simply return an empty List<Customer> if we can’t find our value and we’re good.
However in the case of a method like
Customer GetCustomerByID(Guid CustomerID) {}
You do not have the luxury of returning an empty array. Infact all you can do is return a New Customer(); but then you have a potentially uninitialized object (which you still need to check for) or null.
So what would be the recommended alternative to returning a null in the singular method?
For the single value case consider the
TryGetpatternThis clearly expresses the intent that this method can and will fail and makes it much more awkward to ignore the aspect of failure. Dealing with it correctly though produces very readable code.
Often I like to pair my
TryGetAPIs with a version that throws for those occasions when the caller knows it must be present else it’s a violation of some implicit contract.