Note that there are some explanatory texts on larger screens.

plurals
  1. POjava ternary hack
    text
    copied!<p>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:</p> <pre><code>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; } </code></pre> <p>to this:</p> <pre><code>String method(param) { return param == null ? error0 : param.equals(foo1) ? condition ? bar1 : error1 : param.equals(foo2) ? condition ? bar2 : error2 : ... error } </code></pre> <p>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.,</p> <pre><code> else if (param.equals(foo3)) if (condition) { field = value; return bar3; } else return error3; </code></pre> <p>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):</p> <pre><code> param.equals(foo3) &amp;&amp; (field = value) instanceOf String ? condition ? bar2 : error2 : </code></pre> <p>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.</p> <p>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 "&amp;&amp;" 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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload