Mutating Object State and Implementing Equality

Similar documents
CSE332: Data Abstractions Lecture 19: Mutual Exclusion and Locking

Design Patterns: State, Bridge, Visitor

Programmazione di sistemi multicore

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Software Design and Analysis for Engineers

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Instantiable Classes

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 4 Shared-Memory Concurrency & Mutual Exclusion

Assertions, pre/postconditions

Code Reuse: Inheritance

Building Java Programs

Announcements. Last modified: Fri Sep 8 00:59: CS61B: Lecture #7 1

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

CSCI-1200 Data Structures Fall 2009 Lecture 25 Concurrency & Asynchronous Computing

Safety SPL/2010 SPL/20 1

EXAM Computer Science 1 Part 1

CS 251 Intermediate Programming Methods and Classes

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

CS 251 Intermediate Programming Methods and More

THE UNIVERSITY OF WESTERN AUSTRALIA. School of Computer Science & Software Engineering CITS1001 OBJECT-ORIENTED PROGRAMMING AND SOFTWARE ENGINEERING

APCS Semester #1 Final Exam Practice Problems

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

CS159. Nathan Sprague

Objectives: 1. Introduce the course. 2. Define programming 3. Introduce fundamental concepts of OO: object, class

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

CS111: PROGRAMMING LANGUAGE II

CSCI 161 Introduction to Computer Science

CSE P 501 Exam 8/5/04

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

CPS122 Lecture: Defining a Class

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Recommended Group Brainstorm (NO computers during this time)

Lecture 10: Interfaces

Storing Data in Objects

Exception-Handling Overview

THE UNIVERSITY OF WESTERN AUSTRALIA. School of Computer Science & Software Engineering CITS1001 OBJECT-ORIENTED PROGRAMMING AND SOFTWARE ENGINEERING

C# Programming for Developers Course Labs Contents

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

ITI Introduction to Computing II

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.

COE318 Lecture Notes Week 10 (Nov 7, 2011)

BSc. (Hons.) Software Engineering. Examinations for / Semester 2

ECE 122. Engineering Problem Solving with Java

Catching Defects: Design or Implementation Phase? Design-by-Contract (Dbc) Test-Driven Development (TDD) Motivation of this Course

Assertions. Assertions - Example

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

The class Object. Lecture CS1122 Summer 2008

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Encapsulation. Mason Vail Boise State University Computer Science

ITI Introduction to Computing II

Using the Xcode Debugger

Programmazione di sistemi multicore

Quarter 1 Practice Exam

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

1/27/2014. OO design approach with examples. UML and project clarifications (2) Project clarifications 1. UML

re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS1004: Intro to CS in Java, Spring 2005

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

CS61B Lecture #7. Announcements:

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Subclassing for ADTs Implementation

Defensive Programming

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

CS 61B Discussion 5: Inheritance II Fall 2014

CSCI 200 Lab 3 Using and implementing sets

Object-Oriented Design Lecture 21 CSU 370 Fall 2008 (Pucella) Tuesday, Dec 9, 2007

Checked and Unchecked Exceptions in Java

Making New instances of Classes

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency

Object Oriented Programming. Java-Lecture 11 Polymorphism

In this lab we will practice creating, throwing and handling exceptions.

Practice problem on defining and using Class types. Part 4.

Data Structure. Recitation IV

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

Note that if both p1 and p2 are null, equals returns true.

CSCI 1301: Introduction to Computing and Programming Spring 2019 Lab 10 Classes and Methods

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

sample exam Concurrent Programming tda383/dit390 Sample exam March 2016 Time:?? Place: Johanneberg

Introduction to Design Patterns

Midterm Exam (REGULAR SECTION)

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

CSE331 Winter 2014, Final Examination March 17, 2014 Please do not turn the page until 8:30. Rules:

Why Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018

CS 617 Object Oriented Systems Lecture 5 Classes, Classless World:Prototypes, Instance Variables, Class Variables, This/Self 3:30-5:00 pm Thu, Jan 17

Exceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

The first program: Little Crab

Transcription:

Mutating Object State and Implementing Equality 6.1 Mutating Object State Goals Today we touch the void... (sounds creepy right... see the movie, or read the book, to understand how scary the void can be). We will focus on the following topics: Designing methods that modify (for real) the state of an object Designing tests for effectful methods Java RuntimeExceptions Designing methods that define equality The Problem For this Lab we will work with bank accounts again. For our purposes we have savings accounts, which must maintain a positive balance, checking accounts, which require a minimum balance (not zero), and credit lines, which records the balance currently owed and the maximum the customer can borrow. The bank has a list of Accounts where a customer may deposit or withdraw money. A withdraw from an account cannot reduce the balance below the minimum, and, for credit lines, cause the balance owed to be above the maximum limit. When a customer deposits money to an account, the balance increases, though for a credit line this decreases the amount owed, which cannot drop below zero. 6.1.1 Methods that effect a simple state change 1. Create a Project for this Lab and unzip the files from Lab6.zip, from the main lab page. 1

2. Make examples of Checking, Savings, and Credit accounts. We ve started you off with two of them using a different organization than you are used to. We use a reset() method to initialize the examples, rather than initializing them in place. Follow the same organization with your examples... more on that later. 3. Discuss several scenarios of making deposits and withdrawals with you partner for each type of account. Make sure you understand when the transaction cannot be completed (i.e., is invalid). 4. Add the method withdraw to the Account class and implement it in each subclass: // EFFECT: Withdraw the given amount // Return the new balance abstract int withdraw(int amount); When doing so we encounter a few questions: Question: How do we signal that the transaction cannot be completed? Answer: throw a new RuntimeException similar to the following: throw new RuntimeException("Over credit limit"); Make the message meaningful for your class. You may add some information about the account that caused the problem, the customer name, or the current balance available. Question: How do we test that the method throws the expected exception? Answer: Suppose the method invocation: this.check1.withdraw(1000) should throw a RuntimeException with the message: "1000 is not available". Our test for this exception would then be: t.checkexception("testing withdraw checking", new RuntimeException("1000 is not available"), this.check1, "withdraw", 1000); 2

The first argument is a String that describes what we are testing it is optional and can be left out. The second argument gives the Exception our method invocation should throw (the messages must match exactly). The third argument is the instance that invokes the method, the fourth argument is the method name. After that we list as many arguments as the method consumes, separated by commas. Question: How do we test the correct method behavior when the transaction goes through? Answer: We look at the purpose and effect statements. Because the method produces a value as well an effect (changes the state of the object), we must test both aspects. We first define instances and add them to our reset method. We use the reset method to initialize our data since the examples may change during each test. // Test the withdraw method(s) void testwithdraw(tester t){ reset(); t.checkexpect(check1.withdraw(25), 75); t.checkexpect(check1, new Checking(1, 75, "First Checking Account", 20)); reset(); Notice that we use the reset method twice. At the start we make sure that the data we use has the correct values before the tests are invoked, and after the test(s) we reset the data to the original values (since we always need to reset before testing, we can leave the second reset off, though later we may to different tasks before and after testing). In this case there are two tests we have to perform: the first is what we have done in the past comparing the value produced by the method with the expected value. The second test verifies that the state of the object did indeed change as expected. Try the following incorrect implementations of the withdraw method in the Checking class to see why all this testing is necessary: 3

// Missing Effect... int withdraw(int amount){ return this.balance - amount; // Wrong return value... int withdraw(int amount){ this.balance = this.balance - amount; return amount; // Correct, but no exception! int withdraw(int amount){ this.balance = this.balance - amount; return this.balance; Of course, we need to implement and test the method in each Account class: the Savings and Credit classes as well. 5. Add the method deposit to the Account class and implement it in all subclasses. Remember, what happens in the Credit case when the balance would become negative (no more debt)? // EFFECT: Deposit the given funds into this account // Return the new balance abstract int deposit(int funds); Make sure your tests are defined carefully as before. 6.1.2 Methods that change the state of structured data The Bank class keeps track of all accounts. 1. Design the method openacct to Bank that allow the customer to open a new account in the bank. // EFFECT: Add a new account to this Bank void add(account acct){... Make sure you design your tests carefully. 2. Design the method deposit that deposits the given amount to the account with the given name and account number. Make sure you 4

take exception to any problems, e.g., no such account, or a transaction that cannot be completed. Make sure to design your tests carefully. 3. Design the method withdraw that withdraws the given amount from the account with the given account number. Make sure you take exception to any problems, e.g., no such account, or a transaction that cannot be completed. Make sure to design your tests carefully. 4. Design the method removeaccount that will remove the account with the given account number from the list of accounts in this Bank. // EFFECT: Remove the given account from this Bank void removeaccount(int acctno){... Hint: Throw an exception if the account is not found, and follow the Design Recipe! 6.2 Understanding Equality Note: This material is covered in pages 321-330 in the textbook. Read it carefully. Our object is to define a method that will determine whether a given Account is the same as this account. We may need such a method to find a desired account within the Bank. Of course, now that we have the abstract class it would be easy to compare just account number and the name on the account, but we want to make sure that all the customer s data matches what we have on file exactly, including balances, interest rates, etc. 6.2.1 Implementing same We will design a same method similar to that described in the second part of the lecture, Equality by safe casting. The relevant examples can be found in the lecture notes. You may want to look at the code there as you work through this problem. 1. Begin by designing the method same for the Account class. 5

2. Make examples that compare all kinds of accounts: of the same kind (e.g., Checking vs. Checking) and of different kinds (e.g., Savings vs. Credit). For the accounts of the same kind you should test both true and false cases. Comparing different kinds of accounts should always produce false. 3. Now that you have sufficient examples, follow with the design of the same method in one of the concrete account classes (for example the Checking class). Write the template and think of what data and methods are available. 4. As in lecture, you need two different helper methods: one that determines whether the given account is a Checking/Savings/Credit account, and one that converts this account into the desired type. Design the methods ischecking, issavings, and iscredit, that determine whether this account is a checking/savings/credit account, respectively. 5. Design the methods tochecking, tosavings, and tocredit, that convert this account into a checking/savings/credit account, respectively. Header and purpose for the checking account case: // Convert this Account into a Checking abstract Checking tochecking(); In the Checking class the body will be just // Produce a checking account from this account Checking tochecking(){ return this; While the others should throw a RuntimeException with the appropriate message. 6. Now we can define the body of the same method in the Checking class: // Is the given Account the same as this? boolean same(account that){ if(that.ischecking()){ return this.samechecking(that.tochecking()); else{ return false; 6

7. We still need the method samechecking but this only needs to be defined within Checking, and can be defined with private (or protected) visibility. 8. Complete the design of the same methods (including samechecking, samesavings, samecredit) for the other two account classes. 6.2.2 Alternative approaches: bad and good Bad Option - Incorrect alternative: The method above can be incorrectly written with two features of the Java language: the instanceof operator and casting. In the Checking class this style method would look like the following: // Is the given Account the same as this Checking? boolean same(account that){ if(that instanceof Checking){ return this.samechecking((checking)that); else{ return false; However, this version introduces bugs! The issue is that any class that later extends Checking, say a PremiumChecking class, will also be considered a Checking instance by the instanceof operator. If we implement a similar same method in PremiumChecking: // Is the given Account the same as this PremiumChecking? boolean same(account that){ if(that instanceof PremiumChecking){ return this.samepremchecking((premiumchecking)that); else{ return false; Then now only PremiumChecking objects can be the same as other PremiumChecking instances, But Checking instances can be the same as PremiumChecking instances!! 7

These kinds of bugs can cause serious problems. This issue is also illustrated in the example file BadSame.java from the lab main page. You can add the file to your project and run the example, but we have included the tester output for illustration. Good Option - A Correct alternative: In lecture we introduced another version that also works. It requires us to add a new method to the abstract class for each subclass of Account. For our IShape hierarchy, the methods were: // Is that Circle the same as this Shape? public boolean samecirc(circ that); // Is that Rect the same as this Shape? public boolean samerect(rect that); // Is that Combo the same as this Shape? public boolean samecombo(combo that); This technique is popular in object-oriented languages like Java and is known as double dispatch (or callbacks). 8