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?