Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Shorten conditions  RSS feed

 
Joseph Smithern
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anyway to shorten the below statement?
I need each one but was wondering if there is a way to shorten it someway?
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37234
519
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest thing I can think of is to get rid of the blank if statement. I've paraphrased the original code to make it easier to see what I've changed.



Also, note that the code contains a bug. I think you meant "myvar = 34" and not "myvar == 34". The former sets the value of myvar. The later checks whether myvar is equal to 34 and then ignores the result.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Continuing from where Jeanne left off, you might find it a little more readable to do something like this:

Those last three ifs are a little weird. Note that if, for example, both xBlank and yBlank are true, then myVar gets set twice - first to 41, then to 34. Assuming that 34 is the correct final value, it might make more sense to set the value just once by reversing the order and using if/else statements:

That doesn't look any shorter - but now notice that by the time we get to the third test, we know that z was not blank, and we know that y was not blank. And we know from the previous test that they can't all three be not blank, or we wouldn't have gotten to this part of the code. So the final test is unnecessary:

This way we can clearly see that exactly one of those three things happens. This can be shortened quite a bit using the ternary operator, if you're familiar with it:

which is equivalent to

Those last two forms may be unpopular with a lot of people who aren't used to seeing them, and chances are good you may want to avoid them for that reason. But I included them since you asked about ways to shorten this, and they do shorten the code quite a bit. So we get:

And incidentally, the if statement can also be written

but those are about the same complexity.

You can decide for yourself how much each of these changes really benefits anyone. I think Jeanne's change plus my first change (introducing xBlank etc) definitely help readability. After that, we can make it shorter but not necessarily better. It really depends on your taste.
 
Joseph Smithern
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim,

Thanks, I used your examples and it works great!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!