Balzanka / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Optional.orThrow(Throwable t) #1121

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Optional could be extended by the operation "orThrow(Throwable t)" which would 
be thrown if the value is absent.

Original issue reported on code.google.com by simonsilvalauinger on 27 Aug 2012 at 5:54

GoogleCodeExporter commented 9 years ago
Someone proposed adding this method internally...here's the discussion from API 
review.

Pros:
Allows you to throw app-specific exceptions without rethrowing an ISE or 
checking isPresent separately
If we add Enums.get() that returns an Optional, lots of people catch/rethrow 
checked exceptions and unchecked exceptions...that could become sexier with:
Suit suit = Enums.get(Suit.class, userSuit).orThrow(new 
SuitNotFoundException());
Fits well into a fluent API:
Value value = FluentIterable.from(...).tryFirstMatching(...).orThrow(...);

Cons:
Very similar to what get() already does - unchecked exception for free
but if your only goal is to throw, a bare get() call that doesn’t save the 
result may look too hacky for some
Easy to make a helper method that does this by checking isPresent()
“construct an exception, pass it in to maybe get thrown or not” is not even 
remotely a common pattern
How often do you really want to throw a checked exception (or care that much 
which unchecked exception) when the value isn’t present?
new Throwable has to fill in the stack trace - useless expense
(from the Throwable() javadocs: “The {@link #fillInStackTrace()} method is 
called to initialize the stack trace data in the newly created throwable.“)
Optional’s javadoc lists 14 methods.  Optional feels like it should be way 
smaller and simpler than that. (We felt those methods were justified, but it 
should raise the cost for each additional suggested one.)
if we discount static methods and Object overrides, and collapse overloads, 
it’s really only 5 methods, with orThrow making 6
Encourages other types of exceptions

Decision: NO - too expensive, not a common pattern, can just use !isPresent(), 
throw

Original comment by kurt.kluever on 27 Aug 2012 at 7:19

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:13

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08