Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short IF - ELSE statement

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?

like image 501
monczek Avatar asked Dec 16 '10 14:12

monczek


People also ask

What is shorthand if else statement in Python?

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.

What is if else statement explain with example?

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.


1 Answers

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.

like image 61
Andrzej Doyle Avatar answered Sep 20 '22 21:09

Andrzej Doyle