abstract data types chapter 1. today n data types & abstract data types n designing systems and...

30
Abstract Data Types Abstract Data Types Chapter 1 Chapter 1

Upload: rosa-barker

Post on 02-Jan-2016

226 views

Category:

Documents


3 download

TRANSCRIPT

Abstract Data TypesAbstract Data Types

Chapter 1Chapter 1

TodayToday

Data Types & Abstract Data TypesData Types & Abstract Data Types Designing Systems and ADTsDesigning Systems and ADTs

• use casesuse cases• class-responsibility-collaboration cards (CRC)class-responsibility-collaboration cards (CRC)• unified modeling language (UML)unified modeling language (UML)

An Example ADT: the BagAn Example ADT: the Bag

Data StructuresData Structures

Structure Structure arrangement arrangement• data structure data structure arrangement of data arrangement of data

Some come with programming languageSome come with programming language• data typesdata types

Others developed by programmersOthers developed by programmers• some standardized—various Java packagessome standardized—various Java packages• others built to orderothers built to order

Data TypesData Types

Computer languages offer data typesComputer languages offer data types• int, float, char, array of int, float, char, array of typetype, record of , record of typestypes, …, …

Each type comes with some operations Each type comes with some operations defined for itdefined for it• addition, multiplication, equality check, select addition, multiplication, equality check, select

an element, select a field, …an element, select a field, … Different languages/dialects may offer Different languages/dialects may offer

slightly different optionsslightly different options

Abstract Data TypesAbstract Data Types

““Abstract” means not associated with any Abstract” means not associated with any particular language/dialect/machineparticular language/dialect/machine• data types as they are in mathematicsdata types as they are in mathematics

Data types Data types implementimplement ADTs ADTs• int implements integer, float implements realint implements integer, float implements real• usually restricted somehowusually restricted somehow

Ideal is to make close to the model ADTIdeal is to make close to the model ADT

AbstractionAbstraction

Focus on Focus on whatwhat instead of instead of howhow• car’s controls: gas, brakes, steering wheel, …car’s controls: gas, brakes, steering wheel, …

» whatwhat: accelerate, decelerate, turn, …: accelerate, decelerate, turn, …» howhow: gas? diesel? electric? drum? disk? gears? wire?: gas? diesel? electric? drum? disk? gears? wire?

• for the for the driverdriver, , howhow doesn’t really matter doesn’t really matter» driving an electric car much like driving any otherdriving an electric car much like driving any other

• design for the driver!design for the driver!

ADT PartsADT Parts

Domain of the ADTDomain of the ADT• what values are therewhat values are there

OperationsOperations• functions defined over those valuesfunctions defined over those values• may involve other typesmay involve other types

Note:Note:• no decision on no decision on howhow to represent the values to represent the values• no decision on no decision on howhow to implement the operations to implement the operations

ADTs and InterfacesADTs and Interfaces

Interface specifies Interface specifies whatwhat can be done can be done Does not specify Does not specify howhow it will be done it will be done Interface has no data fieldsInterface has no data fields BUT it’s designed with the data in mindBUT it’s designed with the data in mind

• operations are defined operations are defined on the dataon the data• operations take/modify/return dataoperations take/modify/return data

Java interfaces are data typesJava interfaces are data types

System DesignSystem Design

Actors: who or what will use the system?Actors: who or what will use the system? Scenarios: what will they be doing?Scenarios: what will they be doing? University registration systemUniversity registration system

• actors: student & registraractors: student & registrar• scenarios:scenarios:

» apply (student)apply (student)» enroll (registrar)enroll (registrar)» add course (either)add course (either)» drop course (either)drop course (either)

Develop a ScenarioDevelop a Scenario

““Use Case”: describe actor in scenarioUse Case”: describe actor in scenario• Identify the nouns Identify the nouns look for classes/data look for classes/data• Identify the verbs Identify the verbs look for methods look for methods

Student adding a course:Student adding a course:• Student enters ID informationStudent enters ID information• System confirms student is registeredSystem confirms student is registered• Student selects course and section from list(s)Student selects course and section from list(s)• If there is no time conflict: If there is no time conflict:

» add course to student’s scheduleadd course to student’s schedule

Develop a CRCDevelop a CRC

ResponsibilitiesResponsibilities• Which scenarios? Methods in scenarios?Which scenarios? Methods in scenarios?

CollaborationsCollaborations• Which other classes are involved?Which other classes are involved?

Student’s ScheduleStudent’s Schedule• add a section, remove a section, check for time add a section, remove a section, check for time

conflict, …conflict, …• section (multiple), student (one)section (multiple), student (one)

UML DiagramsUML Diagrams

Semi-formal way to represent informationSemi-formal way to represent information• class/interface nameclass/interface name• datadata• methodsmethods

» + means public+ means public» name: typename: type

Schedule

(list of sections)

+addSection(s: Section)+removeSection(s: Section)+isTimeConflict(s: Section): boolean+show()

UML DiagramsUML Diagrams

Semi-formal way to represent informationSemi-formal way to represent information• lines/arrows for collaborationslines/arrows for collaborations

» numbers on ends: how many of this for eachnumbers on ends: how many of this for each• each schedule has 0 to 10 sections (* each schedule has 0 to 10 sections (* any #) any #)

» arrows: schedule has sections; section no schedulesarrows: schedule has sections; section no schedules

ScheduleStudent Section Course1 1 1* *0..10

UML DiagramsUML Diagrams

Semi-formal way to represent informationSemi-formal way to represent information• open-head arrows for inheritanceopen-head arrows for inheritance• interfaces labeled <<interface>>interfaces labeled <<interface>>

Student

GradStudent UndergradStudent

<<interface>>Measurable

Sample ADT: the BagSample ADT: the Bag

A finite collection of objects in no A finite collection of objects in no particular order, possibly with duplicatesparticular order, possibly with duplicates• compare a list: in some particular ordercompare a list: in some particular order• compare a set: no duplicates allowedcompare a set: no duplicates allowed

Lists, sets and bags are allLists, sets and bags are allcontainerscontainers• object to group other objectsobject to group other objects• similar actionssimilar actions

Use CasesUse Cases

Assume we already went thru this process Assume we already went thru this process and discovered that we need a bagand discovered that we need a bag• a bag is a fairly useful thinga bag is a fairly useful thing

Only collaboration is the kind of things we Only collaboration is the kind of things we want to put into the bagwant to put into the bag

Only responsibilities are the methods for Only responsibilities are the methods for working with the bagworking with the bag

Bag CRCBag CRC

• Responsibilities:Responsibilities:» get # of items currently in bagget # of items currently in bag» see whether bag is emptysee whether bag is empty» add given object to bagadd given object to bag» remove given object from bagremove given object from bag» remove some unspecified object from bagremove some unspecified object from bag» empty the bagempty the bag» check whether some object is in the bagcheck whether some object is in the bag» count duplicates of some object in the bagcount duplicates of some object in the bag» list all objects in the baglist all objects in the bag

• Collaboration: class of objects bag can containCollaboration: class of objects bag can contain

Things Can Go Wrong!Things Can Go Wrong!

Asked to remove item that’s not thereAsked to remove item that’s not there Asked for list element with negative indexAsked for list element with negative index Need to decide what to doNeed to decide what to do BAD things to do:BAD things to do:

• ignore commandignore command» don’t remove anything, don’t warn clientdon’t remove anything, don’t warn client

• try to “fix” the requesttry to “fix” the request» take absolute value of index and return that itemtake absolute value of index and return that item

Dealing with Unusual ConditionsDealing with Unusual Conditions

Make client responsible to avoid itMake client responsible to avoid it• document the “precondition” on the operationdocument the “precondition” on the operation

Return a boolean valueReturn a boolean value• true true that worked; false that worked; false that didn’t that didn’t

Return a special value for failed operationsReturn a special value for failed operations• not a valid return value! (null not a valid return value! (null mightmight work) work)

Throw an exceptionThrow an exception

Bag Operation FailuresBag Operation Failures

When adding an item, bag may be fullWhen adding an item, bag may be full• return true if item was added, false otherwisereturn true if item was added, false otherwise

When removing a specific item, not thereWhen removing a specific item, not there• return true if item was removed, false otherwisereturn true if item was removed, false otherwise

When removing “some” item, empty bagWhen removing “some” item, empty bag• return null (NOTE: can’t keep nulls in the Bag)return null (NOTE: can’t keep nulls in the Bag)

Incorporate these decisions into the designIncorporate these decisions into the design

Bag UML DiagramBag UML Diagram

T is a “generic” typeT is a “generic” type• each bag will specify its own “base” typeeach bag will specify its own “base” type

Bag

+getCurrentSize(): integer+isEmpty(): boolean+add(newEntry: T): boolean+remove(anEntry: T) : boolean+remove(): T+clear(): void+contains(anEnty: T): boolean+getFrequencyOf(enEntry: T): integer+toArray(): T[]

T

* *

Generic Types in JavaGeneric Types in Java

You’ve seen theseYou’ve seen these• ArrayList<Integer>ArrayList<Integer>, , List<String>List<String>, …, …

Use a generic name in the declarationUse a generic name in the declaration» usually one capital letterusually one capital letter

public class ArrayList<B> public class ArrayList<B> // B for “Base”// B for “Base”public interface List<E> public interface List<E> // E for “Element”// E for “Element”public class Bag<T> public class Bag<T> // T for “Type”// T for “Type”

• use that name in the method declarationsuse that name in the method declarationspublic boolean add(T newEntry) { … }public boolean add(T newEntry) { … }

Revised Bag UML DiagramRevised Bag UML Diagram

T is a “generic” typeT is a “generic” type• each bag will specify its own “base” typeeach bag will specify its own “base” type

Bag<T>

+getCurrentSize(): integer+isEmpty(): boolean+add(newEntry: T): boolean+remove(anEntry: T) : boolean+remove(): T+clear(): void+contains(anEnty: T): boolean+getFrequencyOf(enEntry: T): integer+toArray(): T[]

Bag Implementation/InterfaceBag Implementation/Interface

Want to allow multiple ways to implementWant to allow multiple ways to implement• an array, a linked list, a kind of structure that an array, a linked list, a kind of structure that

hasn’t even been invented yet!hasn’t even been invented yet! Each implementation is its own classEach implementation is its own class

• ArrayBag, LinkedBag, QuantumBag, …ArrayBag, LinkedBag, QuantumBag, … For the ADT, we create an interfaceFor the ADT, we create an interface

• BagInterfaceBagInterface

BagInterfaceBagInterface

public interface BagInterfacepublic interface BagInterface<T><T> { { public int public int getCurrentSizegetCurrentSize ();(); public boolean public boolean isEmptyisEmpty ();(); public boolean public boolean addadd ((TT newEntry); newEntry); public boolean public boolean removeremove ((TT anEntry); anEntry); public public TT removeremove ();(); public void public void clearclear ();(); public boolean public boolean containscontains ((TT anEntry); anEntry); public int public int getFrequencygetFrequency ((TT anEntry); anEntry); public public T[]T[] toArraytoArray ();();}}

Document the InterfaceDocument the Interface

Add javadoc comments to the interfaceAdd javadoc comments to the interface Add javadoc comments to all methodsAdd javadoc comments to all methods

(See the text/on-line code)(See the text/on-line code)

Using the ADT BagUsing the ADT Bag

We can use the ADT in our programsWe can use the ADT in our programs On-line shopper program from textOn-line shopper program from text

• bag to put purchased items inbag to put purchased items in• base class Item (name and price)base class Item (name and price)

Overview of programOverview of program• add several items to bagadd several items to bag• remove items one at a time, adding to cost, until remove items one at a time, adding to cost, until

bag is emptybag is empty

Using the ADT BagUsing the ADT Bag

Can use the ADT in other classesCan use the ADT in other classes PiggyBank class from textPiggyBank class from text

• instance variable: a Bag of Coinsinstance variable: a Bag of Coins• base class Coin (value and year minted)base class Coin (value and year minted)

PiggyBank UMLPiggyBank UML• shake to see if emptyshake to see if empty• drop a coin indrop a coin in• shake till coin falls outshake till coin falls out

PiggyBank

coins: BagInterface<Coin>

+isEmpty(): boolean+add(newEntry: Coin): boolean+remove(): Coin

Our First Bag ImplementationOur First Bag Implementation

HumanBagHumanBag• a class that asks the user to hold the baga class that asks the user to hold the bag• user adds/removes items, answers questionsuser adds/removes items, answers questions

Only implements Only implements BagInterface<String>BagInterface<String>• HumanBag not a generic typeHumanBag not a generic type

QuestionsQuestions