Denied equal and not equal

I have been reading code lately

if (! (a == b) ) 

instead

  if ( a != b ) 

in some places.

Obviously, they are logically equivalent, but I wonder if there is any specific reason to use one over the other.

Are there certain circumstances when it is preferable, or is all this just a matter of personal style?

+4
source share
7 answers

I really prefer

 if ( a != b ) 

simply because you have to read less and you quickly understand the message that the programmer wanted to convey.

Remember that programmers spend more time reading code than writing, so the more you can make the code more understandable, the better.

+12
source

This is mostly a style issue (and I prefer "a! = B"), but there may be an actual difference in action if a is an object of a class that does not have either an = = operator or an operator! =.

+9
source

I would avoid

 if (! (a == b) ) 

since it includes two operations where there is one operator

 if ( a != b ) 

which does the same thing. The second is also more readable (at least a little).

A really big problem with

 if (! (a == b) ) 

is that he made me stop and think "what the hell?" Good code should not do this.

+6
source

As already mentioned, languages ​​with operator overloading often do not use a! = For each ==. In this case! (A == b) is essential since a = b is undefined. Also, in context, it might make sense to use (a == b). Although a shorter form is preferred for reasons stated elsewhere on this question, a longer form may be more descriptive in some sets of problems.

+4
source

Your code should be as simple as possible, i.e. fewer statements are better, so a! = b is 3 constructs, not! (a = b), which is 4.

+1
source

Any half-worthy compiler produces the same code (if == and! = Were overloaded, as mentioned elsewhere), so optimization issues are not important.

I don’t think I have ever seen "if (! (A == b))" beyond the larger conditional condition, when it is clearer not to use DeMorgan’s theorem, but I suppose I could see it as a way of emphasizing that these two values ​​really need to be identical, and there is something deeply wrong if they are not. However, the breakthrough of the big "OmgICantBelieveThisHappenedException ()" throw on the next line will be even more clear .:-)

Apart from these two situations, I have to agree with the camp "use! =", As it is more clear when you look at the code. "!" can be easily overlooked, especially with some formatting conventions.

+1
source

This is the DeMorga theorem. (Augustus de Morgan is a mathematician)

Go if (a! = B)

-5
source

All Articles