I'm trying to make my code more readable, so I decided to use some short IF statements.
Here's my code which doesn't work ("not a statement"):
jXPanel6.isVisible() ? jXPanel6.setVisible(true) : jXPanel6.setVisible(false);
What's wrong with this? Needs brackets? Where?
Shorthand If and If Else in Python Shorthand if and if else is nothing but a way to write the if statements in one line when we have only one statement to execute in the if block and the else block.
Definition and Usage The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.
The "ternary expression" x ? y : z
can only be used for conditional assignment. That is, you could do something like:
String mood = inProfit() ? "happy" : "sad";
because the ternary expression is returning something (of type String
in this example).
It's not really meant to be used as a short, in-line if-else
. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).
So the proper way to do this would just be with an if-else block:
if (jXPanel6.isVisible()) { jXPanel6.setVisible(true); } else { jXPanel6.setVisible(false); }
which of course can be shortened to
jXPanel6.setVisible(jXPanel6.isVisible());
Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).
Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With