In computer programming, an assertion is a predicate (for example a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true or false at that place.
An assertions is an executable check for a Boolean expression that must be true.
Assertions contain Boolean expressions that define the correct state of your program at specific points in the program source code.
An assertion has a Boolean expression that, if evaluated as false, indicates a bug in the code. This mechanism provides a way to detect when a program starts falling into an inconsistent state.
Assertions are excellent for documenting assumptions.
Assertions helps developers write code that is more correct, more readable, and easier to maintain.
You can think of assertions as a uniform mechanism that replaces the use of ad hoc conditional tests.
Assertions are used to document (logically impossible|fundamental) situations.
Assertions play an important role in debugging and designing code with testability and design-by-contract style of programming in mind.
Assertions do not:
This code is absolutely loaded with assertions and these are permanently enabled
It's acceptable to spend 5% of the total running time doing assertions checks.
BankAccount acct = null;
// ...
// Get a BankAccount object
// ...
// Check to ensure we have one
assert acct != null;
This asserts that acct is not null. If acct is null, an AssertionError is thrown. Any line that executes after the assert statement can safely assume that acct is not null.
In java:
Although the use of assertions replaces the ad hoc use of conditional tests with a uniform methodology, it does not allow for a repair strategy (as error handling does) to continue program execution.
For instance, the error handling Java exception mechanism with the use of try/catch/finally allows you to process the case instead of aborting the program as in assertions.
This means that when an exception is detected, the program aborts with no recovery mechanism.
With assertions, the program will be larger in size and therefore slower to load. When testing and debugging is completed, assertions do not have to be removed from the program.
Assertions can be compiled out in order to ignore all assertions, instead of deleting them manually.