CS 242 Topics Modularity and Object-Oriented Programming � Modular program development • Step-wise refinement • Interface, specification, and implementation � Language support for modularity John Mitchell • Procedural abstraction • Abstract data types – Representation independence – Datatype induction • Packages and modules • Generic abstractions – Functions and modules with type parameters Reading: Chapter 10 and parts of Chapter 9 Stepwise Refinement Dijkstra’s Example (1969) � Wirth, 1971 begin • “… program ... gradually developed in a sequence of print first 1000 primes refinement steps” end begin • In each step, instructions … are decomposed into variable table p more detailed instructions. fill table p with first 1000 primes � Historical reading on web (CS242 Reading page) print table p begin • N. Wirth, Program development by stepwise end int array p[1:1000] refinement, Communications of the ACM, 1971 make for k from 1 to 1000 • D. Parnas, On the criteria to be used in decomposing p[k] equal to k-th prime systems into modules, Comm ACM, 1972 print p[k] for k from 1 to 1000 • Both ACM Classics of the Month end Program Structure Data Refinement � Wirth, 1971 again: Main Program • 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 Sub-program Sub-program Sub-program Sub-program Sub-program 1
Example Modular program design � Top-down design Bank Transactions • Begin with main tasks, successively refine � Bottom-up design • Implement basic concepts, then combine Deposit Withdraw Print Statement � Prototyping • Build coarse approximation of entire system � For level 2, represent account • Successively add functionality balance by integer variable Print transaction history � For level 3, need to maintain list of past transactions Modularity: Basic Concepts Example: Function Component � Component � Component • Meaningful program unit • Function to compute square root – Function, data structure, module, … � Interface � Interface • float sqroot (float x) • Types and operations defined within a component � Specification that are visible outside the component • If x>1, then sqrt(x)*sqrt(x) ≈ x. � Specification � Implementation • Intended behavior of component, expressed as float sqroot (float x){ property observable through interface 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;} � Implementation return y; • Data structures and functions inside component } Example: Data Type Heap sort using library data structure � Priority queue: structure with three operations � Component empty : pq • Priority queue: data structure that returns elements insert : elt * pq → pq in order of decreasing priority deletemax : pq → elt * pq � Interface � Algorithm using priority queue (heap sort) • Type pq begin • Operations empty : pq empty pq s insert : elt * pq → pq insert each element from array into s deletemax : pq → elt * pq remove elements in decreasing order and place in array � Specification end • Insert add to set of stored elements This gives us an O(n log n) sorting algorithm (see HW) • Deletemax returns max elt and pq of remaining elts 2
Language support for info hiding Abstract Data Types � Procedural abstraction � Prominent language development of 1970’s • Hide functionality in procedure or function � Main ideas: � Data abstraction • Separate interface from implementation – Example: • Hide decision about representation of data structure and implementation of operations • Sets have empty, insert, union, is_member?, … • Sets implemented as … linked list … • Example: priority queue can be binary search tree or • Use type checking to enforce separation partially-sorted array – Client program only has access to operations in interface – Implementation encapsulated inside ADT construct In procedural languages, refine a procedure or data type by rewriting it. Incremental reuse later with objects. Modules Modules and Data Abstraction module Set � Can define ADT � General construct for information hiding interface • Private type � Two parts type set • Public operations val empty : set • Interface: fun insert : elt * set -> set � More general A set of names and their types fun union : set * set -> set • Several related types • Implementation: fun isMember : elt * set -> bool and operations implementation Declaration for every entry in the interface � Some languages type set = elt list Additional declarations that are hidden val empty = nil • Separate interface fun insert(x, elts) = ... and implementation � Examples: fun union(…) = ... • One interface can ... • Modula modules, Ada packages, ML structures, ... have multiple end Set implementations Generic Abstractions C++ Templates � Parameterize modules by types, other modules � Type parameterization mechanism • template<class T> … indicates type parameter T � Create general implementations • C++ has class templates and function templates • Can be instantiated in many ways � Language examples: � Instantiation at link time • Ada generic packages, C++ templates, ML functors, … • Separate copy of template generated for each type • ML geometry modules in course reader • Why code duplication? • C++ Standard Template Library (STL) provides – Size of local variables in activation record extensive examples – Link to operations on parameter type 3
Standard Template Library for C++ Example (discussed in earlier lecture) � Monomorphic swap function � Many generic abstractions void swap(int& x, int& y){ • Polymorphic abstract types and operations int tmp = x; x = y; y = tmp; � Useful for many purposes } • Excellent example of generic programming � Polymorphic function template � Efficient running time (but not always space) template<class T> � Written in C++ void swap(T& x, T& y){ • Uses template mechanism and overloading T tmp = x; x = y; y = tmp; • Does not rely on objects – No virtual functions } � Call like ordinary function Architect: Alex Stepanov float a, b; … ; swap(a,b); … Main entities in STL Example of STL approach � Container: Collection of typed objects � Function to merge two sorted lists • Examples: array, list, associative dictionary, ... • merge : range(s) × range(t) × comparison(u) → range(u) � Iterator: Generalization of pointer or address This is conceptually right, but not STL syntax. � Algorithm � Basic concepts used � Adapter: Convert from one form to another • range(s) - ordered “list” of elements of type s, given • Example: produce iterator from updatable container by pointers to first and last elements � Function object: Form of closure (“by hand”) • comparison(u) - boolean-valued function on type u � Allocator: encapsulation of a memory pool • subtyping - s and t must be subtypes of u • Example: GC memory, ref count memory, ... How merge appears in STL Comparing STL with other libraries � Ranges represented by iterators � C: • iterator is generalization of pointer qsort( (void*)v, N, sizeof(v[0]), compare_int ); • supports ++ (move to next element) � C++, using raw C arrays: � Comparison operator is object of class Compare int v[N]; � Polymorphism expressed using template sort( v, v+N ); template < class InputIterator1, class InputIterator2, � C++, using a vector class: class OutputIterator, class Compare > OutputIterator merge(InputIterator1 first1, InputIterator1 last1, vector v(N); InputIterator2 first2, InputIterator1 last2, sort( v.begin(), v.end() ); OutputIterator result, Compare comp) 4
Recommend
More recommend