Wednesday, April 20, 2005

What is Wrong with This Code

Managing and assisting a project development is more and more interesting to me nowadays. However, from time to time, I will run into some code that I think worth documenting.

What is wrong with this code in a test case:

public void testShowAddressInvalidCountryCode() {
DomainError e= ErrorMsg.AddressInvalidCountryCode;
String msg = ErrorMsg.showErrorMsg(e,new DomainErrorValue(ErrorMsg.PERMANENT_ADDRESS));
assertTrue(msg!="No error msg");
System.out.println(msg);
}
If you don't see why, let me explain:
  • Don't use negative assertions: Asserting two things not equal is most error-prone. If you assert that a return value NOT equals 0, for example, chances are that this test will still pass, even if a bug is to be introduced in the method making it return 6 instead of 5.
  • Don't use instance comparison: If the method decide to create a new copy for return object, then it is impossible to test. For the example here, if the method innocently construct the message "No error msg" instead of returning the constant, the instance check will render useless.
  • Don't do System.out during test: This will pollute the output in the console and make it useless. If it is anything need to be verified, verify it with assertions. ASH project went a little to the extreme but it has very sound reason.
  • Do test-driven development: Code like this is most likely a symptom of lacking test-driven development.

No comments: