Cleaner way to write code snippet - java

I'm new to java and I was wondering if there was an easier way to write
if(a == 10 || b == 10){
//stuff
}
In my mind I tried something like this:
if(a||b == 10){
//stuff
}
because IMO that makes a lot of intuitive sense, but it's not a thing.

if you're only comparing a few values then you might as well proceed with the current approach as there is nothing in place to make it shorter. However, if you're repeating your self many times, then you can create a helper function to do the work for you.
i.e
static boolean anyMatch(int comparisonValue, int... elements){
return Arrays.stream(elements)
.anyMatch(e -> e == comparisonValue);
}
then call it like so:
if(anyMatch(10, a, b)){ ... }

That's not going to work like that. You're checking the value of two variables against a value, which ends up being two checks, if(a == 10 || b == 10).
However, you can modify this check to this code:
if(Arrays.asList(a,b).contains(10))
It results in the same behavior, but this is neither shorter nor easier to read.

Yeah turns out there isn't a way to make it shorter.

No, we can't do it because in case of java, there is no option for comparison of variables like that.
Even you couldn't write like this
if(a||b){ //staff }
but if you would write then you will get this error message
error: bad operand types for binary operator '||'

Not shorter, but more "intuitively" readable:
boolean condA = (a == 10);
boolean condB = (b == 10);
if(condA || condA){
//stuff
}
always keep in mind, the goal isn't to write shortest possible code, but best maintainable code.

Related

can you have two conditions in an if statement

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}

Better way to handle n number of if-else if in java

I was wondering if there is any better way to handle n no. of if/else-if block in Java.
I have a situation where I need to print different values based on n no. of if/else-if/conditions blocks like
if(p==1 && q==r)
System.out.println("Condition 1");
else if(r==p && q==9)
System.out.println("Condition 2");
else if(z==1 && s==r)
System.out.println("Condition 3");
else if(p==1 || x==r && y==7)
System.out.println("Condition 4");
else if(q==z && y==r || p==4)
System.out.println("Condition 5");
else if(x==z && r==5 || z==30)
System.out.println("Condition 6");
else if(s==1 || q==x)
System.out.println("Condition 7");
else if(r==14 || q==r++ || z==y)
System.out.println("Condition 8");
else if(q==18 && s==r || p==90)
System.out.println("Condition 9");
else if(y==19 || q==89)
System.out.println("Condition 10");
...
Is there any other way to handle it instead of putting multiple if/else if statements so that if later on any new condition come, it will be easy to handle it.
The real answer here: don't do that.
In good OO design, you solve this problem in very different ways; for example by using polymorphism. You actually want to avoid having many different sources of information, to then make decisions on that.
In your case; I would be thinking towards FSMs and the state pattern for example.
What I mean is: your code is showing a certain "approach" towards solving a problem. And as long as you keep that approach as is, you are only talking about finding ways to express your solution in the "least ugly" way.
Instead, you should step back and look into approaches that can be expressed in "really beautiful" ways.
Thus: there is no "simple" direct answer to your question. You have to step back and have a close look at the requirements you want to fulfill; to then design a better, "more OO" solution to that.
The minimal thing here: you could start by declaring an enum like:
public enum Condition {
A, B, C, ...
and then you would have some factory method that hides all those statements; like:
Condition currentCondition = determineCondition(p, q, r, z);
switch(currentCondition) {
case A:
Meaning: you want to at least "centralize" that knowledge somewhere to avoid code duplication. But again; that is just like putting some new color on an old, rusty car. It helps for the moment, but doesn't really improve things.
Regarding your comments: yes, the switch is only marginally "better" than if elses. But as you said: you can't make too many chances, so at least you want to have exactly one piece of code that determines state.
But in the end: I think you are approaching this on a wrong level. You are probably dealing with some kind of complicated business logic; and you want to solve that on a low level like this. But nothing you do on such a level will lead to a robust, long-term maintainable solution. Probably the real solution is to step back and look into using some kind of workflow engine.
You can make a Condition (interface or superclass) which accepts all your variables:
public interface Condition {
boolean isConditionMet(int p, int q, int r, int s, int x, int y, int z);
void performAction();
}
For each single Condition you can override/implement a boolean method isConditionMet().
public class C1 implements Condition {
public boolean isConditionMet(int p, int q, int r, int s, int x, int y, int z) {
return p == 1 && q == r;
}
public void performAction() {
System.out.println("Condition 1");
}
}
Then you can put all conditions in a collection, and for each Condition you have you can ask:
if (condition.isConditionMet())
condition.performAction();
Now each Condition object itself is responsible for when it should act, and what it should do then. A perfect separation of concerns.
Downvote bait
When you say "if any new condition come" do you mean you are willing to modify the code if a new condition comes, or must the code adapt without being modified? If the former, I think you've done it the best way. (Though, I would add an if (false){} at the top, so all the real cases look the same, making it easy to rearrange them.) If the latter, then a table-driven approach is needed. Performance is not an issue if every case has a print statement. If you do care about performance, then put the most common cases first.
If you care even more about performance, have a tree of if-statements, rather than a ladder. So, for example, have something like this, so you're not repeatedly asking the same sub-question:
if (p == 1){
.. all the cases where p is 1
} else {
.. all the other cases
}
There may be other OO-related ways to write this, but none of them will be faster or easier to modify than this.

Chained ANDs or chained ORs best practice

Which is better in terms of best practice / efficiency?
if (x == 1
&& y == 1
&& z == 1)
{ do things }
or
if (x != 1 ||
y != 1 ||
z != 1)
{ don't do things and go to a different bit of logic.}
Is there any difference in efficiency when short circuiting ANDs and ORs? Is it (generally) better to check positively or negatively when multiple logical assertions need to be made?
For pure optimization of the code it depends case-by-case. The scenario that will on average do the least amount of comparisons.
For code design it is also case-by-case. The if-cases should match what you are actually looking for. A function that tests if a string is inputted correctly for example. (the tests are made up)
public boolean isValidString (string s) {
if (s.isEmpty())
return false;
if (s.length() < 12)
return false;
if (s...)
return false
return true;
}
In this case the most logical approach is the ||. It could be written.
public boolean isValidString (string s) {
if (s.isEmpty() || s.length() < 12 || s...)
return false;
return true;
}
With http://en.wikipedia.org/wiki/De_Morgan%27s_laws this could be rewritten to not and. However it is not what we want to test, even though they yield the same result.
So stick to the logical approach in general cases.
If you think about efficiency then think about how often each case will occur. The most likely one should be put in front so the whole expression is shortcircuited immediately.
Better you use "==" instead of going for "!=".
This is also recommended with PMD.
The following is good and improves redability.
If(true){
//
}else{
//
}
than
If(!true){
//
}else{
//
}
Well, in some JVM implementations boolean values are stored as integers in the JVM. int value 1 meaning true and int value 0 meaning false. Also, comparison logic at processor level is architecture dependent. Some machines might subtract 2 operands, then add and then compare, others might compare byte by byte etc.. So, unless you are looking at a specific hardware architecture (which you shouldn't.. atleast for java programming language), I don't think this matters much..

Java coding standards and multiple IF's

I have the following lines of code:
if(
checker.this()==false ||
checker.that()==false ||
checker.what()==true||
checker.cool()==false ||
checker.damm()==true
(...)
)
{
option = Option.FALSE;
}
With about 20 checks that must be performed. I've found this to be the most 'visual-tolerable' form of writing this if with multiple OR sequence but I'm not yet satisfied. Is there a coding standard for this?
Thanks.
The closest thing to a coding standard around this is Steve McConnel, whose authoritative book "Code Complete" recommends that complex conditions are factored into their own method, even if they are only used once. This allows for the name of the method to descibe what is happening.
if (checkValid(checker)) {...}
private boolean checkValid(Checker checker) {...}
checkValid is not a good name, of course, and should be replaced with something more descriptive. In this particular case you may want to make the check method part of "checker" object.
You should also avoid "something==true" and "something==false", and use "something" and "!something". This process is helped if you give the boolean methods appropriate names, like "isOpen()", "isEmpty()", rather than "open()" and "empty()". "checker.isOpen() && !checker.isEmpty()" is perfectly clear to read.
foo==false should better be written with !foo
Possibly, you can move this big if in a separate method: if (checker.complexConditionMet()) or if (complexConditionMet(checker)). It will improve readability.
checker.this()==false can be replaced by !checker.this()
I have never heard of a coding standard for anything like this. Personally, I would group several ifs into a method taking readability into consideration. For instance if you have something like:
if (this || that || what || where || why || cool || wow){ ... }
You could replace it with:
if (pronouns() || questions() || exclamations()){ ... }
I'd try to find common meaning between any of the various checks, and create functions from them.
When bundled together to describe a certain discrete, meaningful state of affairs or requirement, this can make the code less magical, easier to read, easier to test.
i.e. something like this, which is a bit "magical"
if (a == "world" || b == "dolly" || c == 42 || murder()) {
}
can be rendered more readable by changing it to something more like this:
if ( canSayHello() || canMeanLife()) {
}
...
boolean canSayHello() {
return a == "world" || b == "dolly"
}
boolean canMeanLife() {
return c == 42 || murder();
}

boolean operation trick

I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.
It's basically a one liner for this:
if (myVar) {
myVar = false;
} else {
myVar = true;
}
It's something like this, but don't know what it's called or the correct syntax of it:
myVar = myVar : false ? true;
How about
myVar = !myVar
?
myVar = myVar ? false : true; is using the conditional operator.
You can just do this though
myVar = !myVar;
Another option is XOR:
myVar ^= true;
It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.
What you are thinking of is the conditional operator:
myVar = myVvar ? false : true;
(As you see, a lot of people call this "the ternary operator", but that only means that it is an operator with three operands. As it happens, there is only one operator with three operands in this language, but it still says nothing about what the operator does.)
It's of course easier to use the negation operator:
myVar = !myVar;
The smallest code I can think of at the moment. I don't know what its called (if it has a name, as you seem to suggest)
myVar = !myVar
What you're talking about is the "ternary" or "conditional" operator, which does an inline substitution as per a condition.
The syntax is:
condition ? trueValue : falseValue
I usually throw parentheses around my condition, sometimes around the whole conditional operator. Depends on how much I'm trying to delineate it from everything else.
So for example, suppose you want to return the larger of two numbers:
public int max(int a, int b)
{
return (a > b) ? a : b;
}
Notice that it can be substituted into the middle of something else.
Okay, now let's tackle your actual question about toggling a boolean type.
myVar = (myVar) ? false : true;
is how you would do it with the conditional operator. (Again, parentheses aren't required, I just favor them.)
But there's a simpler way to toggle the boolean... using the logical NOT ("!") operator:
myVar = !myVar;
Keep it simple. :-)
if(myVar == true)
{
myVar = false;
}
else if (myVar == false)
{
myVar = true;
}
else
{
myVar = FILE_NOT_FOUND
}
This also works :P
v=v?!v:!v;
There is a ternary operator (wikipedia). Which allows you to write a condensed if-else statement like in the second example.
In java:
myVar = (myVar) ? true : false;
There is also the NOT operator, which toggles a boolean variable. In java that is !. I believe that is what you want.
myVar = !myVar;
public boolean toggle(boolean bool)
{
return !bool;
}
I recently (on my own) found a similar answer to one already stated here. However, the simplest and shortest (non-repeating variable name with least code) answer is:
formControl.disabled ^= 1;
This works best in JavaScript when wanting to toggle boolean, DOM-based attributes (for example, a form control/input's disabled property -- going from a non-editable to edit state). After much searching (with no result that I liked) and some trial and error, I found my solution to be the simplest (however, true instead of a 1 would be clearer -- as was previously posted).
Since this syntax isn't very clear, immediately, I would not advise using it very often (I believe it is appropriate when the variable or property makes the context obvious). I have posted this response (instead of making it a comment) because the context in which the XOR bitwise self-assignment should be used is very important. This "trick" should mostly be avoided when considering best practices.
As others have noted, there are two ways to negate something: "lvalue = !lvalue;" and "lvalue ^= 1;". It's important to recognize the differences.
Saying "lvalue = !lvalue" will cause lvalue to be set to 1 if it was zero, and 0 if it was set to anything else. The lvalue will be evaluated twice; this is not a factor for simple variables, but saying "someArray[index1][index2][index3][index4] = !someArray[index1][index2][index3][index4]" could slow things down.
Saying "lvalue ^= 1;" will cause lvalue to be set to 1 if it was 0, 0 if it was 1, and something else if it was neither zero nor 1. The lvalue need only be specified or evaluated once, and if the value is known to be either zero or 1, this form is likely to be faster.
Too bad there's no auto-negate operator; there are times such a thing would be handy.
You can also use the binary form of negation as shown here.
if ((v == true) && !(v = false)) {
v != true; /* negate with true if true. */
} else {
v =! false; /* negate with false if false. */
}

Categories

Resources