Video in progress
How is design by contract (precondition, postcondition, invariant) applied in Java, and how does it relate to LSP?
A precondition is a condition that must hold before a method is called, a postcondition is the result the method guarantees, and an invariant is a rule that is always true during the object's life. By LSP, a child class can't strengthen a precondition or weaken a postcondition.
📖 Answer
Java has no special syntax for contracts; they live in three places:
- Checks in code:
public Money withdraw(Money amount) {
Objects.requireNonNull(amount, "amount"); // precondition
if (!amount.isPositive()) throw new IllegalArgumentException("amount > 0 bo'lishi kerak");
if (balance.lessThan(amount)) throw new InsufficientFundsException(id);
balance = balance.minus(amount);
assert !balance.isNegative() : "invariant buzildi"; // invariant
return balance; // postcondition: the new balance
}
assert is disabled by default (you need -ea), so don't rely on it for production checks, only for internal "can't happen" cases.
-
Javadoc:
@throws IllegalArgumentException if amount is negative,@return never null. -
Types: if the
Moneyvalue object can't be negative, the type itself guarantees the precondition. This is the strongest approach.
How it relates to LSP:
- The parent: "I accept any positive amount". The child: "only up to 1 million". The precondition was strengthened, and code that works through the parent breaks.
- The parent: "I return a sorted list". The child doesn't sort. The postcondition was weakened.
- A child may give extra guarantees (strengthen the postcondition) or accept more input, and that is safe.
The benefit of fail-fast: bad input is rejected at the boundary with a clear message, not three layers deeper with an obscure NPE.
Sign up to mark studied questions and save your progress.