110 likes | 251 Views
Comp 401 Assertions Practical Example and The Importance of Being Earnest. Instructor: Prasun Dewan. Prerequisite. Assertions (Preconditions and Postconditions ). Bank Account with Withdraw. public class ABankAccount implements BankAccount { int currentBalance = 0;
E N D
Comp 401Assertions Practical Example and The Importance of Being Earnest Instructor: Prasun Dewan
Prerequisite • Assertions (Preconditions and Postconditions)
Bank Account with Withdraw publicclassABankAccountimplementsBankAccount { intcurrentBalance = 0; publicstaticfinalint MIN_BALANCE = 100; publicABankAccount (intinitialBalance) { currentBalance= initialBalance; } publicintgetCurrentBalance () {returncurrentBalance; } publicvoid deposit (int amount) {currentBalance+= amount;} publicboolean withdraw (int amount) { intminNecessaryBalance = MIN_BALANCE + amount; if (minNecessaryBalance <= currentBalance) { currentBalance -= amount; returntrue; } elsereturnfalse; } }
Withdrawing one Dollar: Not Allowed Because of Min Balance requirement
Integer.MAX_INT Withdrawing a Large Amount: Allowed
Integer Overflow Most significant bit of positive (negative) numbers is 0(1)
Asserting Withdraw with Pre and Post Conditions publicbooleansafeWithdraw (int amount) { assert amount > 0: "amount < 0"; booleanretVal = withdraw(amount); assertcurrentBalance>= MIN_BALANCE: "currentBalance < MIN_BALANCE"); returnretVal; }
Using Safe Withdraw with MaxInt: The Importance of Being Earnest
Google for “integer overflow security” Integer Overflow in Real Life