Assertions & Invariants
Assertions are Boolean expressions that must be true at specific points in the code. They serve as a debugging aid by catching logic errors early, before they cause downstream problems.
Types of Assertions
+---------------------------------------------------------+
| ASSERTION TYPES |
+---------------------------------------------------------+
| |
| PRECONDITIONS |
| - Must be true BEFORE a method executes |
| - Validates input assumptions |
| - Example: assert age >= 0 |
| |
| POSTCONDITIONS |
| - Must be true AFTER a method executes |
| - Validates the result |
| - Example: assert result >= 0 |
| |
| INVARIANTS |
| - Must be true at all times during object lifetime |
| - True after construction and after every method |
| - Example: assert list.size() >= 0 |
| |
+---------------------------------------------------------+
Using Assertions in Code
public class BankAccount {
private double balance;
private boolean isActive;
public void withdraw(double amount) {
// Precondition
assert amount > 0 : "Withdrawal amount must be positive";
assert isActive : "Account must be active";
assert amount <= balance : "Insufficient funds";
balance -= amount;
// Postcondition
assert balance >= 0 : "Balance cannot go negative";
// Invariant
assert balance >= 0 : "Invariant: balance non-negative";
}
}
When to Use Assertions
- Use for programmer errors โ not user input validation
- Use to document assumptions that should always be true
- Use to catch impossible states in production code
- Don't use for recoverable errors or input validation
Key Takeaways
- Assertions catch bugs early when they are cheapest to fix
- Preconditions, postconditions, and invariants form a contract
- Use assertions to document code assumptions
- Disable assertions in production for performance