Modularity and Object-Oriented ProgrammingReading AssignmentTopicsStepwise RefinementDijkstra’s Example (1969)Program StructureData RefinementExampleModularity: Basic ConceptsExample: Function ComponentExample: Data TypeUsing Priority Queue Data TypeAbstract Data Types (ADT)ModulesModules and Data AbstractionGeneric AbstractionsC++ TemplatesC++ Standard Template LibraryMain Entities in STLExample of STL ApproachMerge in STLSTL vs. “Raw” C and C++Object-Oriented ProgrammingObjectsDynamic LookupOverloading vs. Dynamic LookupEncapsulationSubtyping and Inheritance Object InterfacesSubtypingExampleObject-Oriented Program StructureExample: Geometry LibraryShapesSubtype HierarchyCode Placed in ClassesUsage Example: Processing LoopSubtyping Inheritanceslide 1Vitaly ShmatikovCS 345Modularity andObject-Oriented Programmingslide 2Reading AssignmentMitchell, Chapters 9 and 10slide 3TopicsModular program development• Stepwise refinement• Interface, specification, and implementationLanguage support for modularity• Procedural abstraction• Abstract data types• Packages and modules• Generic abstractions– Functions and modules with type parametersslide 4Stepwise Refinement“… program ... gradually developed in a sequence of refinement steps … In each step, instructions … are decomposed into more detailed instructions.”• Niklaus Wirth, 1971slide 5Dijkstra’s Example (1969)beginprint first 1000 primesendbeginvariable table pfill table p with first 1000 primesprint table pendbeginint array p[1:1000]make for k from 1 to 1000p[k] equal to k-th primeprint p[k] for k from 1 to 1000endslide 6Program StructureMain ProgramSub-program Sub-program Sub-programSub-programSub-programslide 7Data Refinement“As tasks are refined, so the data may have to be refined, decomposed, or structured, and it is natural to refine program and data specifications in parallel”• Wirth, 1971slide 8ExampleFor level 2, represent account balance by integer variableFor level 3, need to maintain list of past transactionsBank TransactionsDeposit Withdraw Print StatementPrint transaction historyslide 9Modularity: Basic ConceptsComponent• Meaningful program unit– Function, data structure, module, …Interface• Types and operations defined within a component that are visible outside the componentSpecification• Intended behavior of component, expressed as property observable through interface Implementation• Data structures and functions inside componentslide 10Example: Function ComponentComponent• Function to compute square rootInterface• float sqroot (float x)Specification• If x>1, then sqrt(x)*sqrt(x) ≈ x.Implementationfloat sqroot (float x){float y = x/2; float step=x/4; int i;for (i=0; i<20; i++){if ((y*y)<x) y=y+step; else y=y-step; step = step/2;}return y;}slide 11Example: Data TypeComponent• Priority queue: data structure that returns elements in order of decreasing priorityInterface• Type pq• Operations empty : pqinsert : elt * pq → pqdeletemax : pq → elt * pqSpecification• Insert adds to set of stored elements• Deletemax returns max elt and pq of remaining eltsslide 12Using Priority Queue Data TypePriority queue: structure with three operationsempty : pqinsert : elt * pq → pqdeletemax : pq → elt * pqAlgorithm using priority queue (heap sort)begin create empty pq sinsert each element from array into sremove elts in decreasing order and place in arrayendslide 13Abstract Data Types (ADT)Prominent language development of 1970sIdea 1: Separate interface from implementation• Example: Sets have operations empty, insert, union, is_member?, …Sets are implemented as … linked list … Idea 2: Use type checking to enforce separation• Client program only has access to operations in the interface• Implementation encapsulated inside ADT constructslide 14ModulesGeneral construct for information hiding• Known as modules (Modula), packages (Ada), structures (ML), …Interface:• A set of names and their typesImplementation: • Declaration for every entry in the interface• Additional declarations that are hiddenslide 15Modules and Data Abstractionmodule Setinterfacetype setval empty : setfun insert : elt * set -> set fun union : set * set -> setfun isMember : elt * set -> boolimplementationtype set = elt listval empty = nilfun insert(x, elts) = ... fun union(…) = ... ...end Set Can define ADT• Private type• Public operations Modules are more general• Several related types and operations Some languages separate interface & implementation• One interface can have multiple implementationsslide 16Generic AbstractionsParameterize modules by types, other modulesCreate general implementations • Can be instantiated in many ways• Same implementation for multiple typesLanguage examples:• Ada generic packages, C++ templates (especially STL –Standard Template Library), ML functors, …slide 17C++ TemplatesType parameterization mechanism• template<class T> … indicates type parameter T• C++ has class templates and function templatesInstantiation at link time• Separate copy of template generated for each type• Why code duplication?– Size of local variables in activation record– Link to operations on parameter typeRemember swap function?• See lecture notes on overloading and polymorphismslide 18C++ Standard Template LibraryMany generic abstractions• Polymorphic abstract types and operations• Excellent example of generic programmingEfficient running time(but not always space)Written in C++• Uses template mechanism and overloading• Does not rely on objects – no virtual functions!Architect: Alex Stepanovslide 19Main Entities in STLContainer: Collection of typed objects• Examples: array, list, associative dictionary, ...Iterator: Generalization of pointer or addressAlgorithmAdapter: Convert from one form to another• Example: produce iterator from updatable containerFunction object: Form of closure (“by hand”)Allocator: encapsulation of a memory pool• Example: GC memory, ref count memory, ...slide 20Example of STL ApproachFunction to merge two sorted lists (concept)• merge : range(s) × range(t) × comparison(u) → range(u)• range(s) - ordered “list” of elements of type s, given by pointers to first and last elements• comparison(u) - boolean-valued
View Full Document