I have this ugly code:
if ( v > 10 ) size = 6;
if ( v > 22 ) size = 5;
if ( v > 51 ) size = 4;
if ( v > 68 ) size = 3;
if ( v > 117 ) size = 2;
if ( v > 145 ) size = 1;
return size;
How can I get rid of the multiple if statements?
I have this ugly code:
if ( v > 10 ) size = 6;
if ( v > 22 ) size = 5;
if ( v > 51 ) size = 4;
if ( v > 68 ) size = 3;
if ( v > 117 ) size = 2;
if ( v > 145 ) size = 1;
return size;
How can I get rid of the multiple if statements?
The obvious answer is to use Groovy:
One liners are always better. Returns 7 for the undefined case where v <= 10.
Yet another variation (less pronounced than the answer by George)
My commenting ability isn't turned on yet, hopefully no one will say "rightfully" based on my answer...
Pretty-ing up the ugly code could/should be defined as trying to achieve:
IMO the answer given by org.life.java was the prettiest and extremely easy to read. I also liked the order in which the conditions were written, for reasons of reading and performance.
Looking over all the comments on this subject, at the time of my writing, it appears that only org.life.java raised the issue of performance (and maybe mfloryan, too, stating something would be "longer"). Certainly in most situations, and given this example it shouldn't bear a noticeable slowdown however you write it.
However, by nesting your conditions and optimally ordering the conditions can improve performance [worthwhile, particularly if this were looped].
All that being said, nesting and ordering conditions (that are more complex than your example) brought on by determination to achieve as fast as possible execution will often produce less readable code, and code that's harder to change. I refer again to #3, pragmatism... balancing the needs.
This is my code sample, using SortedSet. You initialise boundaries once.
Then use it subsequently this way for multiple values of v (and initialised size)
It is interesting that there are plenty of beautiful answers for a simple "ugly" question. I like mfloryan's answer best, however I would push it further by removing the hard-coded array inside the method. Something like,
It now becomes more flexible and can process any given array in descending order and the method will find the index where the value 'v' belongs.
PS. I cannot comment yet on the answers.