1

Should a function have validations (null-checks) for its service dependencies or should that be handled by a try/catch.

A specific example for such a scenario is for e.g if you look at this class User with the function ClearDefaulter where this function clears the user from the list of defaulters that it maintains of users who may have defaulted on some actions. These may be a very few >1% of the user base and hence called infrequently. This function depends on a service defaulterservice that provides the CRUD operations for defaulters. Having the defaulterservice running is an expected scenario so before using it in the function is it recommended to a null check or enclose it in a try/catch and handle it as an unexpected exception.

function bool IsValidUser(User user, DefaulterService defaulterService, EntitlementService entitlementService)
{
  if defaulterService == null || entitlementService == null)
  {
    //Handle error on the service
    return;
  }
  if (user != null )
  {
    if (entitlementService.IsValidUser(user))
       service.ClearDefaulter(user);
 }

}

Or

function bool IsValidUser(User user, DefaulterService service)
{
  try
  {
    if (user != null)
    {
      if (entitlementService.IsValidUser(user))
                                                service.ClearDefaulter(user);

    }
  }
  catch(Exception ex)
  {
    // Handle all exceptions
  }
}             

I think the benefit of using try/catch is that only the real business function is captured in the try block and that improves readability. The drawback is its not as performant as doing a simple if validation. What would be the recommendation?

Krzysztof Janiszewski
  • 3,763
  • 3
  • 18
  • 38
  • As a general rule I would suggest doing the null checks, but from a practical point of view when there are a lot of things to check, sometimes try/catch is easier and can help you protect against future exceptions you may not have thought of. If the only thing that will throw an error here is the null, I would check for the null. It's more explicit and it shows what you're looking for to future coders. While you could have a complicated try/catch block that shows the same thing, I believe an if statement is better from a performance point of view as well. – user1274820 Sep 06 '19 at 14:52
  • See this answer: https://stackoverflow.com/a/651651/1274820 also, keep in mind that stackoverflow is not for these types of questions. That's better for a code review site. This will probably be downvoted and closed, but I figured I'd give you an answer before that happened. – user1274820 Sep 06 '19 at 14:54
  • Thanks for the reply and the link. It answers what I was looking for. From what I understand in the example above a try catch may better because the services being null is an exception and not a regular situation or a business function – Reshma Raveendran Sep 06 '19 at 22:46

0 Answers0