Reputation: 81
I understand, Assertions are used in tests to check if the programmer's pre- and post- conditions are true and if the assertions fail, there is/are bug/bugs that need to debugged and fixed.
An assertion is a software construct where the developer states ("asserts") a condition that he believes will always be true. If the condition evaluates to false in some languages an exception is thrown, in others a message is printed, and in others the program ceases to operate.
"A message is printed" highlighted in the above definition caught my attention.
My question is, can we extend the use of assert statements in the actual code itself and catch AssertionErrors to log the messages and not just tests? Basically to avoid too much verbose with if-else statements(I hate if-else btw, personally). For example, all of below
String response = aMethod(sendSomething);
if (response!=null && response!="") {
//blah blah
} else {
log.error("Response is null");
throw new NoDataFoundException();
}
could be replaced with the below that provides more detailed messages.
try{
assertThat(aMethod(sendSomething), notNullValue());
} catch (AssertionError e) {
log.error(e.getMessage());
}
Upvotes: 2
Views: 2267
Reputation:
You don't want to catch an assertion failure(*). By definition, the program is operating outside its design perimeter. The only safe thing to do is get out.
(*) OK, you can catch it if the point of catching it is to log whatever you anticipating you'll need to diagnose the problem, and then get out quickly.
In your example, it appears that after testing for a response and logging the failure, you'll carry on inline. In general, that would be a bad idea, but perhaps this was just a quick illustration on your part and should not be taken too literally.
As to what I take to be your overall point: yes, if you're checking pre/postconditions at all, leave the checks in shipping code.
My code would look like:
response = aMethod(sendSomething);
if (response == null || response.isEmpty())
throw new InternalError("....");
and there would be something catching the error at some outermost layer, a point of exception handling being that you can transfer control far away rather than having to deal with everything at the point it occurs -- especially if "it can't happen".
Upvotes: 3