Here is a code snippet that checks if the variable maritialStatus is the same as the constant variable MARRIED.

It does so by checking if the boolean maritialStatus == MARRIED, which evaluates to a true or false value.

final boolean MARRIED = true;
boolean maritialStatus;
..
if(maritialStatus == MARRIED){
   // do something
}

Because the variable maritialStatus is a boolean, it is possible to simplify the condition.

final boolean MARRIED = true;
boolean maritialStatus;
..
if(maritialStatus){
   // do something
}

Here comes accidental assignment.

Note that it is perfectly legal to have assignment in the if-condition checking clause. i.e. maritialStatus = MARRIED because the expression evaluates into a boolean.

In here, the developer has made an accidental typo error of using the assignment operator (=) as opposed to comparison operator (==).

Such mistakes are usually painful and hard to debug as they are not compile time checked.

final boolean MARRIED = true;
boolean maritialStatus;
..
if(maritialStatus = MARRIED){
   // do something
}

Therefore, a recommended way of writing the above code.

This way, since the variable MARRIED is a final constant, an accidental assignment will cause a compile time error.

final boolean MARRIED = true;
boolean maritialStatus;
..
if(MARRIED == maritialStatus){
   // do something
}

An accidental assignment will cause a compile-time error.

final boolean MARRIED = true;
boolean maritialStatus;
..
// this will not compile
if(MARRIED = maritialStatus){
   // do something
}

Usefulness of Accidental Assignment Principle in null checking

First rule, don’t, second rule, don’t. This is not smart.

The Java compiler checks that the left operand of the if condition evaluates to a boolean , there will be no need to apply the accidental assignment principle on a null checking expression.

String obj = getSomething();
// this is absolutely obsolete, since the left operand is not a boolean value  // and would trigger a compilation error for warning if(null == obj){
  // do something
}
String obj = getSomething();
// this will trigger a compilation error for warning, it will not accidentally assign null to // obj thereafter no need for yoda conditions
if(obj = null){
  // do something
}

Conclusion

In conclusion, apply the practice of the mistakes made in accidental assignment when performing evaluation of boolean expressions. This way you avoid logic errors that are hard to catch.

See Google Code Project Home if you would like to download the source code for this post.

Revision 

September 30, 2011 Added section on null checking.

Share