Difference between !(a==b) and a!=b - java

Last week in high school my IT teacher gave us a programm, where one part she wrote interested me a lot.
In an if-statement, she checked if an element of an array was not null, so the programm could proceed with this element, therefore she wrote:
if (!(array[i] == null), which confused me, because with this method you are just using a bracket more, which makes it less easy to read. I changed it to ìf (array[i] != null) and it worked just fine. But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine? Is there some detail I don't know about?

There is no difference in the semantics of the two expressions. I would say there is no good reason to ever write the former.
But now I am confused, because as a teacher I assume you know a lot of your subject, so could there be a good reason why she used her method over mine?
The best thing to do is to ask your teacher. The most important thing to remember about teachers - as human beings - is that they have experiences, prejudices and are fallible.
In other words, she might have been bitten by some problem in the past which was solved by writing it like this - ask her about it, you might learn something.
Or, she perhaps thinks it's better, and can't articulate a strong benefit over personal preference; or that was the way she learnt, and hasn't seen a strong need to change - you learn something from that, insofar as there is more than one way to articulate the same semantics.
(I have a strong preference for != because it's neater - fewer parentheses; and why would the language designers bother providing != if you weren't intended to use it - but these are my personal preferences).
Or, she maybe meant to use !=, and forgot to go back to fix it. It's easy to forget to clean things up.

In Java, there is no difference between a!=b and !(a==b). Choosing the later form is a stylistic choice, which, to be honest, most static analysis tools/IDEs will issue a warning about.

Your teacher is using other ways to write the if-statement.
It doesn't matter if you write
if(array[i] != null)
or
if(!(array[i] == null))
because ! defines as not in most programming language. In this situation both of them are equal.
In conclusion, you can choose whatever style you like.
Hope you understood and good luck!
Always ask your teacher when you wonder about something :)

The other answers are correct. For your example there is no difference - chose what you like the most. But I'd like to give some more reasons to chose one way over the others.
My advice would be not to go for if (! (...)) in general because:
Most people wouldn't do it like this. You will have to read and understand code written by others and others will have to read and understand your code. Quirks like that greatly reduce the redability and collegues will frown upon you.
Some projects might follow a coding standard that doesn't allow this.
Think about the execution. For more complex statements the different style might have an impact. Think of !(A || B || C || D) vs !A && !B && !C && !D. It might happen that in the former A-D have to be evaluated and then the resulting boolean is flipped wheras in the latter it might be enough to see that !A evaluates to false and you can already stop there (because any conjunction with a false member will be false).
But also think about readability again. Actually it might be easier to grasp writing NOT(is_a_digit OR is_a_letter OR is_a_dot) instead of
NOT(is_a_digit) AND NOT(is_a_letter) AND NOT(is_a_dot).
That being said, it's also good to know about Yoda-style writing which is kinda related. Imagine you have String someString; that might contain a string or might be null. Now imagine you'd like to check if its equal to "some specific string": someString.equals("some specific string") - yikes, this might produce a NPE because when someString is null there is no method equals to call on it. Instead you'd have to do someString != null && someString.equals("...") or the Yoda-way of "some specific string".equals(someString). There's also other helpers like Objects.equals().
Sometimes extra parenthesis can make things easier to grasp and sometimes they don't.
While I don't agree that "there are no stupid question" I'd say that sometimes it's better to ask a dumb question than falling behind in the lessons because something nags at you or you missed some important bit. In this case I'd consider this a good question (unless she just told you why).

There is a difference between a!=b and !(a==b), it depends on personal preference and what code you're using. In python a!=b is faster, as other answers have stated.

Actually there is no difference between if (!(array[i] == null) and ìf (array[i] != null)
In this case we can imagine a scenario. Lets say array[i] is not null, then for the first expression inside if(!(false)) , eventually !(false) will be true.
And for the second expression the return result will be directly true.
So seconnd expression is recommended always.

The former is not a good idea in some languages like python,
In python, for former the better way is
if not something==somethingElse
although for latter its perfect, if something != somethingElse,
So learning the former might get you in some situations where the bug is so subtle that debugging gets really hard, especially when you use this condition in while loop

!= is more efficient than !(). I ran a test in python, and it speaks for itself.
(not a and not b and not c and not d) 10.07692837715149
(not (a and b and c and d)) 11.208963394165039

Related

Ternary operation in setter VS Classic If

Currently working on modifying big mapping classes and some new rules have appeared making me wonder what is the best option here.
Imagine a classic mapping function like so:
yyy.setType(xxx.getType);
yyy.setSomething(xxx.getSomethigElse);
yyy.setThisAsWell(xxx.getThatAsWell);
And I now have a condition to check, what would be better? (knowing that I won't have future similar condition checking to do):
final Boolean isRuleApplying = xxx.getRule == RULE;
yyy.setType(
isRuleApplying ? RULE_STUFF : xxx.getType
);
yyy.setSomething(
isRuleApplying ? RULE_STUFF_OTHER : xxx.getSomethigElse
);
yyy.setThisAsWell(
isRuleApplying ? RULE_STUFF_AGAIN : xxx.getThatAsWell
);
Or is it better to use the old if else?
if (xxx.getRule == RULE) {
yyy.setType(RULE_STUFF);
yyy.setSomething(RULE_STUFF_OTHER);
yyy.setThisAsWell(RULE_STUFF_AGAIN);
} else {
yyy.setType(xxx.getType);
yyy.setSomething(xxx.getSomethigElse);
yyy.setThisAsWell(xxx.getThatAsWell);
}
I feel that using ternary operation make it less maintainable and adds more complexity (checks everytime). But I wanted to get some other opinions.
Note: I have a bunch of try..catch so using if means duplicating those try blocks or adding an if in every block which kind of kills readability.
There's no absolute answer to this question. It depends.
With the ternary operator, you immediately see:
Three properties are always set to some value, and it's always the same properties, independent of the condition.
You see the two alternative values close to one another, so for a reader it's easy to compare them.
But there are some (many?) developers who arent't used to that operator (is that their fault or ours?), so using it might force them to look up its meaning instead of immediately understanding the code (to me, having a LISP background, the ternary operator always was as least natural as the if statement).
And it's true, with the ternary operator, you end up with three conditionals instead of one (but you should ignore these minor performance effects unless you find out that it really hurts in your application).
On the other hand, with the if statement, you immediately see:
It's just one condition that influences all properties.
You see the properties combinations for the two situations close together.
And even Java beginners will understand your code.
So, it depends on:
the Java fluency of your co-workers
whether you want to stress the different values for the single properties or the value-sets for the three properties.
And of course, all this isn't very object-oriented. If code structure and budget allow, maybe you could come up with a solution using polymorphism instead of the conditionals.

Could Assertions be used for maintaning loop invariants and checking program correctness

I recently saw this question and thought that the person who asked question is correct to some degree. The answer informed that we should not use assertions to perform any tasks in our program.
But assertions can act as easy one liners for maintaining loop invariants and program invariants , so that we can check program correctness to a degree.
And why are the assertions necessary even if we have if else?? It just tests a Boolean expression similar things could be done from if -else ladders or so then why bother creating a new keyword Assertion??
A 'task in your program', in context, means something that should be done, and ideally tested for.
Not only is:
assert p != null
shorter and simpler than:
if (p == null) throw new IllegalArgumentException("p is null");
making it an assert clearly documents the fact that it is an internal constraint, not a specified behavior. So you don't need another 4 lines testing it.
Of course, sometimes explicitly specified behavior is what you want, e.g public long-lived APIs.
In other words, while they are similar, it's slightly wrong to use an assert where if/throw is correct, and vice versa.
Nevertheless, a lot of Java code doesn't bother with assert, as that leaves one less decision to make. I'm not sure it would be added to the language if it didn't exist...

What is the preferred way to write boolean expressions in Java

I have always written my boolean expressions like this:
if (!isValid) {
// code
}
But my new employer insists on the following style:
if (false == isValid) {
// code
}
Is one style preferred, or standard?
I prefer the first style because it is more natural for me to read. It's very unusual to see the second style.
One reason why some people might prefer the second over another alternative:
if (isValid == false) { ... }
is that with the latter you accidentally write a single = instead of == then you are assigning to isValid instead of testing it but with the constant first you will get a compile error.
But with your first suggestion this issue isn't even a problem, so this is another reason to prefer the first.
Absolutely the first. The second betrays a lack of understanding of the nature of expressions and values, and as part of the coding standard, it implies that the employer expects to hire very incompetent programmers - not a good omen.
Everybody recognizes this snippet:
if (isValid.toString().lenght() > 4) {
//code
}
I think your second example looks at the same direction.
It was discussed for C# several hours ago.
The false == isValid construct is a leftover from C-world, where compiler would allow you to do assignments in if statement. I believe Java compilers will warn you in such case.
Overall, second option is too verbose.
IMO the first one is much more readable while the second one more verbose.
I would surely go for the 1st one
You are evaluating the variable, not false so the latter is not correct from a readability perspective. So I would personally stick with the first option.
I'm going to attempt a comprehensive answer here that incorporates all the above answers.
The first style is definitely to be preferred for the following reasons:
it's shorter
it is more readable, and hence easier to understand
it is more widely used, which means that readers will recognize the pattern more quickly
"false==..." rather than "...==false" is yet another violation of natural order,which makes the reader think "is there something strange going on that I need to pay attention to", when there isn't.
The only exception to this is when the variable is a Boolean rather than a boolean. In that case the second is a different expression from the first, evaluating to false when isValid is null as well as when it is Boolean.FALSE. If this is the case there are good arguments for using the second.
The second style doesn't require you to negate the expression yourself (which might be far more complicated than just "isValid"). But writing "isValid == false" may lead to an unintended assignment if you forget to type two ='s, hence the idiom is to put on the right side what can't be an rvalue.
The first style seems to be preferred among people who know what they're doing.
I just want to say I learned C twenty years ago in school and have moving onto Perl and Java and now C# which all have the same syntax and...
I think (!myvar) is the most popular
I think (myvar==false) is just fine too
in 20 years i have NEVER EVEN SEEN
(false==myvar)
I think your boss is smoking something-- I'm sorry but I'd take this as a sign your boss is some kind of control freak or numbskull.

Using double negatives to test for conditions

To validate user inputs, I am unsure of which of two alternatives is better
1
isNull( Object input )
2
notNull( Object input )
apache's commons lang library chose #2 but I am uncomfortable with double negatives. What do you say ?
To me, double negatives is always a bad thing.
I'd say stick to isNull. Checking for nullity then makes sense while reading.
The opposite would be
if (! isNull(o) )
// ...
which reads out "if not is null". Sure it sounds retarded read out loud, but it makes more sense than checking for nullity with option #1.
if (! isNotNull(o))
// ...
A statement which makes you rewind and say "hey, wait a minute... if not is not...".
But if there is a standard already with having negatives in method names, stick to it. Standards are good things, and should not be broken just because someone is "uncomfortable".
I am uncomfortable with functions which are longer than the code they replace.
I would use x == null or x != null. I agree that double negative isn't clear either.
A puzzle for you, when is (s != s) true? A good example of confusing behaviour. ;)
Honestly, I don't think it makes much difference.
If you are designing your own API, implement it the way you are most comfortable with. Indeed, there's no strong reason to not to implement both isNull and notNull if that makes you feel happier.
But I think it would be silly to abandon plans to use some third-party library solely because you are "uncomfortable with" double negatives. They really aren't that confusing.
The answer here depends on so many considerations, of which some are:
What does your programming environment support most naturally?
What does other similar code in the same project do?
What coding standards are you working to, if any?
Which approach is easier to understand for others reading your code?
If you want a more considered answer, do let us know some more of the details. In the meantime, my top tip would be to go for whatever enhances readability of the code: you want to give future maintainers as much help as you can.
I am a little confused by the question. If the methods in question are just returning a boolean depending upon whether the argument is null, then == null or != null are much better.
However, the reference to Apache Commons Lang seem to indicate that this is validity checking, and an appropriate exception should be thrown is the reference is null. In that case you can't invert the output easily.
FWIW, it looks as if JDK7 will introduce a notNull method, as discussed on an appropriate mailing list, something along the lines of:
public static <T> T notNull(T obj)
Used as:
import static java.util.Object.notNull;
public final MyClass {
private final Thing thing;
public MyClass(Thing thing) {
this.thing = notNull(thing);
}
...

Is defining a "ProbableBugException" code smell, paranoia or good practice?

In my Java code, I occasionally run into situations where I have to catch a checked exception from a library function that I'm pretty sure can't occur in my use case.
Also, when coding, I sometimes notice that I'm relying on certain inputs from other modules (my own) to have or not have particular features. For example, I might expect a string to be in a certain format etc. In these situations, I would often put in a verification step, although I control the code that send the input myself.
At the moment, I'm working on a quite complex product that I want to be very reliable. Among other things, I want it to collect information from caught exceptions and automatically file bug reports. For the above two scenarios, I therefore defined an (unchecked) "ProbableBugException", that tells me I made a mistake in the code delivering the input data.
Is that a) stupid, b) paranoid or c) good practice? This is going to be subjective, I'll put up three wiki answers so we can vote away without rep warping.
ETA:
Thanks to Svend for pointing out that Java has assertions, I didn't realize that. Assertions are actuall pretty much what my question was about, but I only knew them from C and have never used them there.
I'm thinking that using an assert is what you really want there ("probably bug").
It's stupid, because:
the exception should be much more specific, like InvalidInputException
you should think harder about the input side, it's likely that it's shaky if you feel you need that kind of exception
It's good practice, because:
you might have a coworker coding on the input side and the two of you might have misunderstood each other
if you make a mistake, fixing it becomes trivial
in situations where the input side is a plugin of some sort, it helps the plugin developers (who might be external) to deliver correct input.
I always expect the unexecpected.
I often have code like this : ( $div will never be 0 into my code )
if( $div != 0 ) {
$var = $var2 / $div;
} else {
/*
* It should never happen
*/
throw Exception( 'relevant message' );
}
I always protect myself from me and the others

Categories