Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be returned if not null when value cannot be found

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?

like image 768
Maxim Gershkovich Avatar asked Dec 28 '22 04:12

Maxim Gershkovich


1 Answers

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;
}
like image 165
JaredPar Avatar answered Jan 14 '23 15:01

JaredPar