For direct debugging purposes from within source code.
Inserting an assertion means comparing a result against its needed value.
The developer assumes that at the checked line a condition is true. If the condition fails, that shows a bug.
EXAMPLE FOR ASSERTS:
Normally, the assertions are not evaluated since they are for debugging purposes.
In order to force the compiler to evaluate, use the next formulas.
EXAMPLE FOR FORCING THE COMPILER TO EVALUATE:
EXAMPLE FOR ENABLING ASSERTIONS:
EXAMPLE FOR USING ASSERTS:
Using assertions helps to find bugs directly where they can appear.
They are automatically removed from production code at runtime, so they will not slow down the flow.
They make the code more readable, and help remove boilerplate code.
Using them increases the confidence that the code functions correctly.
Assertions should not be used for checking arguments of a method. In case a developer uses a method with wrong parameters, the method should throw the right exceptions.
Do not use assertions to invoke methods which would run normally. By disabling assertions, these methods will not be reachable at runtime.
EXAMPLE FOR WRONG USAGE:
EXAMPLE FOR CORRECT USAGE:
After a code part, in case there can be unwanted results, using assertions.
EXAMPLE FOR CHECKING AGAINST VALUE:
Marking unreachable code: not executed code parts.
EXAMPLE FOR CHECKING UNREACHABLE CODE:
Checks the code which normally would be marked with a comment, and forcing the developer to check the code in case something had been changed above.
This usage prevents the comment to be out-dated as well; having an out-dated comment means a mis-lead to the developer.
EXAMPLE FOR DOCUMENTING WITH ASSERT: