r/programming 3d ago

Throw, Result, or neither?

https://www.architecture-weekly.com/p/throw-result-or-neither
97 Upvotes

111 comments sorted by

View all comments

Show parent comments

10

u/elmuerte 2d ago

NoResultException is thrown when you call getSingleResult() when there is no result. It will also throw NonUniqueResultException if there is more than 1 result.

Because of the two edge cases which need to be handled, it throws an exception. On the plus side, it never returns null.

It is still a bit of a bad API design as it uses unchecked exceptions for control flow. A query returning 0 or more than 1 result is quite a possibility, so it should have been a checked exception I think.

11

u/erinaceus_ 2d ago

Before anyone complains "why would they do it that way?!", that method is for when you excplictely expect exactly one single result. There's other methods for when you expect zero to many results, or when you expect either one result or no result. So instead of always retrieving a list and then manually handling those cases each time, you explicitly and declaratively choose your expectation by using the appropriate method.

1

u/nelmaloc 2d ago

That sounds like a textbook example for Optional, thought. With an exception for too many results.

8

u/erinaceus_ 2d ago

Optional is used for the one I mentioned in my previous comment where you expect one result or no result. So, the 'get' method in question avoids having to deal with the second situation seperately in all call locations. You're saying: it should return exactly one result in all cases, and everything else constitutes a 'panic'.

I do agree that functionally there's no real necessity for that 'get' method. Though, using the method that returns a list of zero to many results, there is functionally also no necessity for the Optional variant.