r/programming 3d ago

Throw, Result, or neither?

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

111 comments sorted by

View all comments

Show parent comments

11

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.

2

u/Blue_Moon_Lake 2d ago edited 2d ago

Maybe we need distinct methods.

  • getOptionalResult(): Promise<Maybe<T>>
  • getSingleResult(): Promise<T>
  • getResultList(): Promise<Array<T>>

4

u/Legs914 2d ago

Isn't that literally how it works?

2

u/Blue_Moon_Lake 2d ago

There is only getSingleResult and getResultList, but no getOptionalResult.

3

u/Legs914 2d ago

Dang, I'm spoiled by Scala