Misuse of the unary-not operator (!)
Coming from a background in C Programming, I am very familiar with the "!" or unary-not operator. This operator inverts the value of the operand it is applied to, so that a true operand returns false, and a false operand returns true. As a programmer often involved in the maintenance of other people's code, I am also very familiar with wading through pages and pages of software that appears little better than hieroglyphics.
Unary-not was widely used back in the days of C, and C++ to an extent, because the language didn't have a built in "null". Some programmers or libraries would use "0" as the null, some would use "-1". There was no consistent way to check if a condition was true, so unary-not did the job.
These days, in "modern" languages such as Java, C# and VB.NET we have the null value, which is assigned to any reference type variable by default. This means that we can write sensible statements like this:
if (myReferenceType != null)
{
// do something
}
I like code that says exactly what it's doing - in the case above, it says "if myReferenceType is not null, do something". Consider the unary-not approach
if (!myReferenceType)
{
// do something
}
Reading that out, we have "if not myReferenceType, do something". What does that statement mean? It doesn't make sense when you read it. What if the unary-not operator has been overloaded?
Unary-not is often also applied to boolean values. Which allows us to do some frankly nasty things. Consider the following:
if (!myClass.IsAvailable())
{
// do something
}
"If not myClass is available, do something". If myClass isn't available, do something. Now consider:
if (!myClass.IsNotAvailable())
{
// do something
}
"If not myClass is not available, do something". If myClass is not not available, do something. Or even:
if (!myClass.IsAvailable()==True)
{
// do somsething
}
"If not myClass is available is true, do something".
As you can see, we can weave all sorts of syntactical loops that are difficult to get out of. Whilst the choice of names for method calls is important (and I will focus on that in a later post) the unary-not operator is causing problems.
Part of the issue with unary-not is that it doesn't preclude the programmer from using it with other logic operators - so you can, as above, combine it with a method call that you are comparing against a boolean value, and invert the result of the entire statement to produce your eventual value.
My final beef with unary-not is that it's very difficult to spot. Unlike an "==False" or a "<>0" it hides itself at the start of a statement, as far as it's possible to get from the functional parts of the code. As a maintenance programmer it is easy to miss, and of course it changes the whole idea of what you're reading.
For your own good, and for maintenance programmers who come after you, don't use unary-not!
