java ternary hack
So I'm not going for maintainability or elegance here.. looking for a way to cut down on the total tokens in a method just for fun. The method is comprised of a long nested if-else construct and I've found that (I think) the way to do it with the fewest tokens is the ternary operator. Essentially, I translate this:
String method(param) {
if (param == null)
return error0;
else if (param.equals(foo1))
if (condition)
return bar1;
else
return error1;
else if (param.equals(foo2))
if (condition)
return bar2;
else
return error1;
...
else
return error;
}
to this:
String method(param) {
return
param == null ?
error0 :
param.equals(foo1) ?
condition ?
bar1 :
error1 :
param.equals(foo2) ?
condition ?
bar2 :
error2 :
...
error
}
However, there are a couple cases where in addition to returning a value I also want to change a field or call a method; e.g.,
else if (param.equals(foo3))
if (condition) {
field = value;
return bar3;
}
else
return error3;
What would be the cheapest way to do this token-wise? What I'm doing now is ugly but doesn't waste too many tokens (here the field is a String):
param.equals(fo开发者_运维问答o3) && (field = value) instanceOf String ?
condition ?
bar2 :
error2 :
Again, the point is not good coding, I'm just looking for hacks to decrease the token count. If there's a shorter way to write the entire thing I'm open to that as well. Thanks for any suggestions.
Edit: Each word and punctuation mark counts as one token. So, for example, "instanceOf String" is two tokens, but "!= null" is three. The main things I can see for possible improvement are the "&&" and the parentheses. Is there a way to put "field = value" somewhere besides the conditional, and if not is there a construct that makes "field = value" a boolean without the need for parentheses?
(field = value) instanceof String
Assuming that it already satisfies your needs (and it thus includes returning false when value
is null
), a shorter alternative would then have been
(field = value) != null
Or if you actually overlooked that and want to make null
return true
as well, then use
(field = value) == value
This can be made much shorter if you use 1-letter variable names.
Further I don't see other ways and I agree with most of us that this all is somewhat nasty ;)
if param is null, return 0
Then make a case/switch/select statement on the parameter. That's clean .
精彩评论