I've read Defensive Programming vs Exception Handling? and if/else statements or exceptions, but none contain something relevant to what I'm searching for.
Taking into account that exception handling is more computational expensive than just carefully designing your code and avoiding certain scenarios, I recently came to the following question: what is the computational complexity "threshold" over which Exception Handling should be preferred?
In my case, I am receiving data from an external middleware and some times fields are null. There are two cases I can handle this.
First
try {
if (user.departNameEn.Equals(selectedUser)
|| user.departNameFr.Equals(selectedUser)
|| user.departNameDe.Equals(selectedUser)) {
string fileName = AppDomain.CurrentDomain.BaseDirectory
+ @"Images\Users\" + user.Id + user.ShortName + ".png";
if (File.Exists(fileName))
{
retVal = fileName;
return retVal;
}
}
}
catch (NullReferenceException e)
{
continue;
}
Second
if (!string.IsNullOrEmpty(user.departNameEn)
&& !string.IsNullOrEmpty(user.departNameFr)
&& !string.IsNullOrEmpty(user.departNameDe)
&& !string.IsNullOrEmpty(user.Id)
&& !string.IsNullOrEmpty(user.ShortName)) {
if (user.departNameEn.Equals(selectedUser)
|| user.departNameFr.Equals(selectedUser)
|| user.departNameDe.Equals(selectedUser)) {
string fileName = AppDomain.CurrentDomain.BaseDirectory
+ @"Images\Users\" + user.Id + user.ShortName + ".png";
if (File.Exists(fileName))
{
retVal = fileName;
return retVal;
}
}
}
Intuitively, the first approach is much more clean and elegant than the second one but which of these is computationally less expensive? Where do the limits of defensive programming end?
Note to duplicate report: As I explained in the introduction, I've read the two main topics for Exception Handling vs Defensive Programming but what I'm actually asking is something different and very specific: when Defensive Programming becomes computationally more expensive than just simplifying your code and adding a single try-catch
statement?
selectedUser.Equals(user.departNameEn)
instead.