1 / 11

Comp 401 Assertions Practical Example and The Importance of Being Earnest

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;

nat
Download Presentation

Comp 401 Assertions Practical Example and The Importance of Being Earnest

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Comp 401Assertions Practical Example and The Importance of Being Earnest Instructor: Prasun Dewan

  2. Prerequisite • Assertions (Preconditions and Postconditions)

  3. 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; } }

  4. Using Withdraw

  5. Withdrawing one Dollar: Not Allowed Because of Min Balance requirement

  6. Integer.MAX_INT Withdrawing a Large Amount: Allowed

  7. Resulting Balance

  8. Integer Overflow Most significant bit of positive (negative) numbers is 0(1)

  9. 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; }

  10. Using Safe Withdraw with MaxInt: The Importance of Being Earnest

  11. Google for “integer overflow security” Integer Overflow in Real Life

More Related