Assertions

Well, one of the most usable feature of safe codding is assertions.
Assertions help to prevent executing code with usafe or unchecked data, for example, with null or wrong parameters, empty strings, too long strings, empty arrays or lists can be unforeseen arguments and must be checked before using.

You may remember the asserts from JUnit. Remember:

assertNotFalse(a > 5, "a cannot be equal or less then 5");

Well, in Apache Commons Lang library you may use the org.apache.commons.lang.Validate class to validate arguments or state in your code. You may use it next:

void saveEntity(Entity entity) {
Validate.notNull(entity);
}

Then, if entity value is then java.lang.IllegalArgumentException is thrown. In other case next code is executed.

There is also overloaded version of such assert methods in Validate class or in JUnit, that helps to describe the assertion:

void saveEntity(Entity entity) {
Validate.notNull(entity, "Entity cannot be null.");
}

I am the fun of the overloaded version of assert methods. Truly say, I think that only version with string description of assertion has right to live. That helps developers to find the source of problem quickly and also it may be used to process the errors.
The other point is to have assert-liked-validation also for state, that will throw the java.lang.IllegalStateException. This type of assertion should used for checking the result of calculation or processing, but not for arguments. So we could have something like:

void saveEntity(Entity entity) {
ArgumentAssert.isNotNull(entity, "Entity cannot be null.");

// create or update the entity,
// then returns entity id, that must be not null value if everything is OK
Integer entityId = dao.save(entity);

StateAssert.isNotNull(entityId, "Entity is not saved, because entity id is null.");
}

The code is not the best, but this shows how StateAssert should be used.

So, if the entityId is null, then StateAssert.isNotNull() method throws IllegalStateException. Before that, ArgumentAssert.isNotNull() method checks whether entity is not null and throws IllegalArgumentException if it is.


And every assert methods, should check whether assertions are enabled, for example, by using system properties.

And what about assert statement in Java?
It should be used, but one type of assertions support must be choosed.

No comments: