Here is some code that is more or less a "daily" pattern:
public static Value getValue() {
if ( cond1 ) {
return val1;
}
if ( cond2 ) {
return val2;
}
if ( cond3 ) {
return val3;
}
throw new AnyException();
}
At the very first glance, it seems to be able to collapse into a single return
statement preserving short-circuit computation like this:
public static Value getValue() {
return cond1 ? val1 :
cond2 ? val2 :
cond3 ? val3 :
throw new AnyException() // it could be a legal piece of code in Java
// if the `throw` statement could be an expression
;
}
However, it's not legal, because throw
is a statement keyword, not an expression. I've tried the following workaround using a generic method:
// Exceptions.java
// Just pretend to let the compiler think it's not an exception statement
public static <T, E extends Throwable> T exception(E ex) throws E {
throw ex;
}
...
// Return.java
public static Value getValue() {
return cond1 ? val1 :
cond2 ? val2 :
cond3 ? val3 :
Exceptions.<Value, AnyException>exception(new AnyException());
}
The the last line in the return
statement looks ugly because:
- verbose syntax and required type parameterization;
- a static import directive cannot be used here.
Is there an elegant way to make that code a little nicer? Thanks in advance.
(I still must use Java 6)
EDIT:
Well, three years later, this feature is suprisingly implemented for C# 7.0. I find it really useful and natural, and not complicated. Example:
public string GetFirstName()
{
var parts = Name.Split(" ");
return parts.Length > 0
? parts[0]
: throw new InvalidOperationException("No name!");
}
Lucky C# guys.