Athari / YaLinqo

Yet Another LINQ to Objects for PHP [Simplified BSD]
https://athari.github.io/YaLinqo
BSD 2-Clause "Simplified" License
439 stars 39 forks source link

Distinct exception cases should have distinct exception types #37

Closed Bilge closed 6 years ago

Bilge commented 6 years ago

single() currently throws UnexpectedValueException for two distinct cases:

  1. The case where there are no matches, as well as
  2. the case where there are too many matches.

It is still possible to distinguish these exception cases by exception message, but it is preferable to catch different types rather than inspect the message because messages are subject to change and type comparison is faster, more succinct to write and clearer.

Athari commented 6 years ago

Exceptions are for exceptional behavior, not for normal control flow. If you handle these cases differently, it means that they're not exceptions, but regular cases. Consider using singleOrDefault (it returns the only element of a sequence, or a default value if the sequence contains no elements) or some combination of first, firstOrDefault, count etc., depending on what cases your code handles.

Exceptions are very expensive and handling them requires complex syntax. Don't use them for control flow.

Bilge commented 6 years ago

That's a good point, and I probably do want singleOrDefault() here. However, this does not invalidate the point that distinct exception types should be thrown instead of shared between different cases.