So, I've been having a little bit of an argument with a fellow coder lately. Specifically: We've been arguing about the proper use of Try / Catch
and If / Else
as well as First() / Single()
in a specific scenario.
Variation #1 - His approach
var items = Search(dto.number); // Returns a List of Objects
if (items.Count = 1)
{
wPerson = items.First();
}
else
{
return;
}
Variation #2 - I changed his code to this.
var items = Search(dto.number); // Returns a List of Objects
try
{
wPerson = items.Single();
}
catch
{
// Handle exception
return;
}
We expect the result of var items = Search(dto.number);
to always be 1.
The Question: Which changes were nescessary? I am trying to defend my point of view below. Please correct me.
First of all: The Single()
. I always try to be as specific as possible and I decided on the following rules:
- First --> Accepts N
- FirstOrDefault --> Accepts 0 and N
- Single --> Accepts 1
- SingleOrDefault --> Accepts 0 and 1
First()
may have worked but it wasn't 100% specific, so I considered it wrong since we had an option to be even more specific.
Secondly: Try / Catch
vs If / Else
. Since I had already changed First()
to Single()
, I considered the if
statement to be redundant. Yes. I know that Try / Catch
is less performant than the If
statement but we expect to have NOTHING BUT 1 result. And if we get more or less, I expect it to be a mistake and with Try / Catch
I'd actually treat it that way.
Am I so off here?
Aucun commentaire:
Enregistrer un commentaire