Short IF - ELSE statement - java

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?

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.

jXPanel6.setVisible(jXPanel6.isVisible());
or in your form:
jXPanel6.setVisible(jXPanel6.isVisible()?true:false);

The ternary operator can only be the right side of an assignment and not a statement of its own.
http://www.devdaily.com/java/edu/pj/pj010018/

As others have indicated, something of the form
x ? y : z
is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.
Perhaps you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

I'm a little late to the party but for future readers.
From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the ! operator?
jxPanel6.setVisible(!jxPanel6.isVisible);
It's not an if statement but I prefer this method for code related to your example.

You can do it as simple as this, I did it in react hooks :
(myNumber == 12) ? "true" : "false"
it was equal to this long if function below :
if (myNumber == 12) {
"true"
} else {
"false"
}
Hope it helps ^_^

Related

Java - Syntax, what does this mean? [duplicate]

I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

java code formats

I'm really sorry for what must be a really stupid question. I don't exactly have formal training in java and a lot of times, when looking through code, I might see something like:
( ) ? :
as in something like:
for (str == null) ? getString(this) : dontGetit(nope.this);
honestly i don't even know exactly it is or if it's remotely close, but hopefully one could recognize the scheme. I was hoping one could perhaps link some documentation on this because i have trouble even searching for it.
It is ternary operator in Java. Read here : http://www.janeg.ca/scjp/oper/ternary.html
it an ternary operator used to evaluate boolean expressions. It is equivalent to if-else statement.
Syntax:
variable_name= (boolean expression) ? value to assign if true : value to assign if false
using terenary operator:
boolean isHappy = true;
String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!";
using if-else:
if(isHappy) {
mood="I'm Happy";
}
else {
mood = "I'm, Sad!";
}
this is conditional or ternary operator in java
( a ) ? b : c;
if a is true b will be executed or run
if a is false c will be executed or run
It's the ternary operator . It's good in sets, and a shortcut for iteration
java ternary operator
Here's an easy ex.:
boolean isObese = true;
String mood = (isObese == true)?"I need to quit fast-food!":"I'm healthy!";
..source
It's called ternary operator, it can be allocated to a variable and it is equivalent of an if-then-else statement.
Have a look at this tutorial and pay attention on something that hasn't been underlined enough by the other answers: the fact that the ternary operator is an expression that can be allocated to a variable or can be returned directly by a method. It has a functional feel into it.

String.equals() argument ordering

I recently received a downvote for using the following in a recent answer:
String word = ...;
if ("s".equals(word) || "y".equals(word)
The downvote was given due to using a "yoda condition". I asked for further explanation but none was provided. I prefer this style to avoid a possible NullPointerException.
Is this a poor coding style? If so, why?
Bill Pugh asked this question at Devoxx 2011. The vast majority of people went for the form "xyz".equals(str). I am with Bill, now preferring str.equals("xyz").
It's fundamental to the Java tradition that we find errors as early as reasonably possible. NPEs are exceptionally common. We want to route these nulls out as soon as possible.
If you're expecting the reference to maybe null, then I don't particularly object to the backwards notation. It's nice to be explicit and easier to understand that there may be a null with a separate null check, but the reverse order should be well understood and sufficiently differentiate the code from the normal case where null is forbidden.
Working in security, some of the bugs null-tolerance accommodates are vulnerabilities.
Yoda conditions (i.e. putting a constant before a variable in a comparison) can be considered bad practice as it makes the line of code less comprehensible. In this specific case however I would state that using a Yoda condition makes the code more comprehensible as you don't have to put a extra null check in front of it.
Visit the following link to understand what is meant by Yoda Conditions|Notation
Its not a "poor coding style" its diferent way of coding.
Yoda can be usefull to track typos in some languages, i believe the -1 was not deserved to be honest but that is my personal opinion.
But Yoda can be bad as explained in this lengthy but very interesting article.
End of the day, there are supporters in favor and against this kinda of notation.
Well, it depends. If in your program "word" should never be null, word.equals("s") may actually be better. If for some obscure reason "word" will become null, you will get NullPointerException.
Think about it. If you get exception, you know something went wrong, and you can faster find mistake and fix it. If program will continue to work silently, and produce wrong results, it will be much harder to detect the problem. Actually, you may not notice there is the problem at all.
It all depends.
There are several reasons not to do it like that, however in the end it depends on you (or the team working on your product) if you think this is bad coding style. Arguments against it are:
Strings are rarely null (and you shouldn't make APIs where they are because people don't expect it)
It feels weird to put the value you are comparing to first
Code style uniformity is important, because this way is the exception, you should only do it, if everyone in your team does it.
As said I don't think these arguments are very strong, nor is the reason to do it like you. So it is mostly important to just agree on one way as your coding style and stick to that.
TL;DR; This definitely is poor coding style NOT :D
well, the yoda conditions are useful in languages where non-boolean can evaluate to a boolean value, e.g.
int test = 0;
if ( test ){ /* do something */
but this is not allowed in Java so you don't run into problems such as forgetting '=', e.g.
if ( test = 2 ){ /* do something */
instead of test == 2
the compiler will not let you do this. So the yoda condition may seem unnatural to someone who has not had to care about this (because he/she didn't use any other language but Java).
This definitely is NOT poor coding style it is just not very common to see Java code using it
yoda condition is where oup put the literal in front of the variable.
word.equals("s") is read as "word equals s"
"s".equals(word) a human reads as "s equals word"
Our brains read the first example much better and the code is clearer.
the only reason imho to use yoda conditions is to prevent assignment
as in "if (42 = i)" instead of "if(42 == i)"
You can write
if (word != null && (word.equals("s") || word.equals("y")))
instead of
if ("s".equals(word) || "y".equals(word))
In this case, first one will never cause any NullpointerException, but in my point of view in this case the 2nd one is better, though it is in Yoda Condition
There is a special case pf Yoda conditional I've not seen defended, or attacked, in any of the answers, so I'll add it for reference. This is the style of:
if(0 < x && x <= max) {
A Yoda conditional because the constant (0) is before the variable (x). The argument against Yoda conditionals is that is hinders readability. Contrast that example with the functionally equivalent
if(x <= max && x > 0) {
Do you really think that, non-Yoda variant, is more readable? I don't.
For readability when using ordering relational operators (<, <=, >, >=), I prefer the style of these heuristics:
Use consistent ordering relations: > is consistent with >=, but not with < or <=; < is consistent with <=.
Prefer < and <= to > and >=, as the default is ascending order.
Place conditions that impose a lower bound on the variable before conditions that impose an upper bound, if using < and <=. Do the opposite if using > and >=.
This very often produces a Yoda conditional for the lower bound.
One might argue that you should (unit-)test your code enough to be confident that nulls don't go where they're not supposed to. This should obviate the need for yoda conditions.

Best Practice: if(foo== false) or if(!foo) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the preferred way to write boolean expressions in Java
Today, me and my colleague raked up an argument.
Which is a better way to use the boolean variables in Java code along with if statements.
boolean foo=true
//1.
if(foo == false)
// do something
else
// do something else
//2.
if(!foo)
// do something
else
// do something else
I support [1], since I think it's more readable.
What do you guys think?.
Number 2, along with "foo" having a descriptive name, so that the code reads well:
if (!hasPurple)
...
I find #2 more readable. I think every Java dev (I'm a C# dev) would know what ! means. I
While probably not the point here, I prefer to put my "true" block as the statement. If the condition is generally going to be false, then I name my variable to represent
if (notFoo)
// do something when
else
// do something else
I find it a good idea to avoid things like
if (foo == true){}
because occasionally you might write
if (foo = true){}
as a typographical error. Often times it's an easy mistake to spot, but it just seems to lend itself well to making that quick mistake.
When using boolean variable as a condition in statement, don't compare it with true.
Not a mistake, but bad style, As it's already a boolean value, so just use it.
Reasons why "!foo" is better
than "foo == false". Referenced from
Conciseness: assuming that you are in a context where a boolean is
required, and "x" is a boolean, it is
less characters to write "x" than "x
== true", or "!x" than "x == false".
Convention: seasoned programmers in Java (or C, C++, C# and most other
languages) expect to see "x" rather
than "x == true", and "!x" rather
than "x == false".
Robustness: in Java the conditional and loop statements all require a
boolean valued expression in the
condition. If "y" is not a boolean,
then a typo of the form "if (y = foo)
{" will give a compilation error in
Java. But if "y" is a boolean then
"if (y = foo) {" does not give a
compilation error. Hence, by avoiding
"==" for booleans you avoid setting
yourself up for a whole raft of bugs
resulting from typos.
I go for 2 because as a programmer even 2 is readable.
Imagine you have hundreds of such validation check do you always check with false.
No
If you are the only one who is going to maintain your code then you are free to use whatever style you like.
Having said that !foo is favored by most of the developers I know.
Its a matter of opinion. I prefer number 2 because its less code to write and I think it is just as readable.

Is it bad practice to change state inside of an if statement?

I wrote some code that looks similar to the following:
String SKIP_FIRST = "foo";
String SKIP_SECOND = "foo/bar";
int skipFooBarIndex(String[] list){
int index;
if (list.length >= (index = 1) && list[0].equals(SKIP_FIRST) ||
list.length >= (index = 2) &&
(list[0] + "/" + list[1]).equals(SKIP_SECOND)){
return index;
}
return 0;
}
String[] myArray = "foo/bar/apples/peaches/cherries".split("/");
print(skipFooBarIndex(myArray);
This changes state inside of the if statement by assigning index. However, my coworkers disliked this very much.
Is this a harmful practice? Is there any reason to do it?
Yes. This clearly reduces readability. What's wrong with the following code?
int skipFooBarIndex(String[] list){
if(list.length >= 1 && list[0].equals(SKIP_FIRST))
return 1;
if(list.length >= 2 && (list[0] + "/" + list[1]).equals(SKIP_SECOND))
return 2;
return 0;
}
It's much easier to understand. In general, having side effects in expressions is discouraged as you'll be relying on the order of evaluation of subexpressions.
Assuming you count it as "clever" code, it's good to always remember Brian Kernighan's quote:
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
...However, my coworkers disliked this very much...
Yes, it is. Not just because you can code it like that, you have to.
Remember that that piece of code will eventually have to be maintained by someone ( that someone may be your self in 8 months )
Changing the state inside the if, make is harder to read and understand ( mostly because it is non common )
Quoting Martin Fowler:
Any fool can write code that a computer can understand. Good programmers write code that humans can understand
There's an excellent reason not to do it: it's makes your code really hard to understand and reason about.
The problem is that the code would generate multiple-WTFs in a code review session. Anything that makes people go "wait, what?" has got to go.
It's sadly easy enough to create bugs even in easy-to-read code. No reason to make it even easier.
Yes, side effects are hard to follow when reviewing code.
Regarding reasons to do it: No, there is no real reason to do it. I haven't yet stumbled upon an if statement that can't be rewritten without side effects without having any loss.
The only thing wrong with it is that it's unfamiliar and confusing to people who didn't write it, at least for a minute while they figure it out. I would probably write it like this to make it more readable:
if (list.length >= 1 && list[0].equals(SKIP_FIRST)) {
return 1;
}
if (list.length >= 2 && (list[0] + "/" + list[1]).equals(SKIP_SECOND)) {
return 2;
}
Borrowed from cppreference.com:
One important aspect of C++ that is related to operator precedence is the order of evaluation and the order of side effects in expressions. In some circumstances, the order in which things happen is not defined. For example, consider the following code:
float x = 1;
x = x / ++x;
The value of x is not guaranteed to be consistent across different compilers, because it is not clear whether the computer should evaluate the left or the right side of the division first. Depending on which side is evaluated first, x could take a different value.
Furthermore, while ++x evaluates to x+1, the side effect of actually storing that new value in x could happen at different times, resulting in different values for x.
The bottom line is that expressions like the one above are horribly ambiguous and should be avoided at all costs. When in doubt, break a single ambiguous expression into multiple expressions to ensure that the order of evaluation is correct.
Is this a harmful practice?
Absolutely yes. The code is hard to understand. It takes two or three reads for anyone but the author. Any code that is hard to understand and that can be rewritten in a simpler way that is easier to understand SHOULD be rewritten that way.
Your colleagues are absolutely right.
Is there any reason to do it?
The only possible reason for doing something like that is that you have extensively profiled the application and found this part of code to be a significant bottleneck. Then you have implemented the abomination above, rerun the profiler, and found that it REALLY improves the performance.
Well, I spent some time reading the above without realising what was going on. So I would definitely suggest that it's not ideal. I wouldn't really ever expect the if() statement itself to change state.
I wouldn't recommend an if condition having side-effects without a very good reason. For me, this particular example took several looks to figure out what was going on. There may be a case where it isn't so bad, although I certainly can't think of one.
Ideally, each piece of code should do one thing. Making it do more than one thing is potentially confusing, and confusing is exactly what you don't want in your code.
The code in the condition of an if statement is supposed to generate a boolean value. Tasking it with assigning a value is making it do two things, which is generally bad.
Moreover, people expect conditions to be just conditions, and they often glance over them when they're getting an impression of what the code is doing. They don't carefully parse everything until they decide they need to.
Stick that in code I'm reviewing and I'll flag it as a defect.
You can also get ternary to avoid multiple returns:
int skipFooBarIndex(String[] list) {
return (list.length > 0 && list[0].equals(SKIP_FIRST)) ? 1 :
((list.length > 1 && (list[0] + "/" + list[1]).equals(SKIP_SECOND)) ? 2 : 0);
}
Though this example is less readable.
Speaking as someone who does a lot of maintenance programming: if I came across this I would curse you, weep and then change it.
Code like this is a nightmare - it screams one of two things
I'm new here and I need help doing the right thing.
I think I am very clever because I have saved lines of code or I have fooled the compiler and made it quicker. Its not clever, its not optimal and its not funny
;)
In C it's fairly common to change state inside if statements. Generally speaking, I find that there are a few unwritten rules on where this is acceptable, for example:
You are reading into a variable and checking the result:
int a;
...
if ((a = getchar()) == 'q') { ... }
Incrementing a value and checking the result:
int *a = (int *)0xdeadbeef;
...
if (5 == *(a++)) { ... }
And when it is not acceptable:
You are assigning a constant to a variable:
int a;
...
if (a = 5) { ... } // this is almost always unintentional
Mixing and matching pre- and post-increment, and short-circuiting:
int a = 0, b;
...
if (b || a++) { ... } // BAD!
For some reason the font for sections I'm trying to mark as code is not fixed-width on SO, but in a fixed width font there are situations where assignment inside if expressions is both sensible and clear.

Categories

Resources