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 TryGet
pattern
bool TryGetCustomerByID(Guid CustomerID, out Customer customer) { }
This 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.
Customer c;
if (container.TryGetCustomer(id, out c)) {
...
} else {
// Deal with failure
}
Often I like to pair my TryGet
APIs 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.
Customer GetCustomerByID(Guid id) {
Customer c;
if (!TryGetCustomerByID(id, out c)) {
throw new Exception(...);
}
return c;
}
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