Modularity and Object-Oriented Programming John Mitchell CS 242 Reading: Chapter 10 and parts of Chapter 9.

Slides:



Advertisements
Similar presentations
Type Systems and Object- Oriented Programming (III) John C. Mitchell Stanford University.
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
CMSC 202 Fall 2010, Advanced Section Designing with Objects.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
CPS 506 Comparative Programming Languages Abstract Data Type and Encapsulation.
1 Modularity Shani Bard Based on a lecture by John Mitchell Reading: Chapter 9.
Modularity and Object-Oriented Programming John Mitchell CS 242 Reading: Chapter 10 and parts of Chapter 9.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Data Abstraction and Modularity Slides today from John Mitchell.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Object Oriented Programming Daniel Albu Based on a lecture by John Mitchell Reading: Chapter 10.
Lecture 9 Concepts of Programming Languages
1 ES 314 Advanced Programming Lec 2 Sept 3 Goals: Complete the discussion of problem Review of C++ Object-oriented design Arrays and pointers.
Abstract Data Types and Encapsulation Concepts
Concepts in Object-Oriented Programming Languages Slides Today Taken From John Mitchell.
C++ fundamentals.
OBJECT ORIENTED PROGRAMMING IN C++ LECTURE
1 CSC241: Object Oriented Programming Lecture No 07.
Slide 1 Vitaly Shmatikov CS 345 Modularity and Object-Oriented Programming.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Chapter 11 Abstract Data Types and Encapsulation Concepts.
Chapter 11 and 12: Abstract Data Types and Encapsulation Constructs; Support for Object Orientation Lesson 11.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
Ceg860 (Prasad)L6MR1 Modularity Extendibility Reusability.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
The Procedure Abstraction, Part V: Support for OOLs Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled in.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
OOP Class Lawrence D’Antonio Lecture 3 An Overview of C++
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
OBJECT-ORIENTED PROGRAMMING (OOP) WITH C++ Instructor: Dr. Hany H. Ammar Dept. of Electrical and Computer Engineering, WVU.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
SOFTWARE DESIGN. INTRODUCTION There are 3 distinct types of activities in design 1.External design 2.Architectural design 3.Detailed design Architectural.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
1 CSCD 326 Data Structures I Software Design. 2 The Software Life Cycle 1. Specification 2. Design 3. Risk Analysis 4. Verification 5. Coding 6. Testing.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Abstraction ADTs, Information Hiding and Encapsulation.
Chapter 10, Slide 1 ABSTRACT DATA TYPES Based on the fundamental concept of ABSTRACTION:  process abstraction  data abstraction Both provide:  information.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Overview of C++ Templates
Object-Oriented Programming Chapter Chapter
ADT data abstraction. Abstraction  representation of concepts by their relevant features only  programming has two major categories of abstraction process.
Principles of programming languages 10: Object oriented languages Isao Sasano Department of Information Science and Engineering.
1 Chapter 11 © 1998 by Addison Wesley Longman, Inc The Concept of Abstraction - The concept of abstraction is fundamental in programming - Nearly.
1 CS Programming Languages Class 22 November 14, 2000.
(1) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
ISBN Chapter 12 Support for Object-Oriented Programming.
Data Abstraction and Modularity
Principles of programming languages 10: Object oriented languages
Abstract Data Types and Encapsulation Concepts
CS 326 Programming Languages, Concepts and Implementation
ABSTRACT DATA TYPES Based on the fundamental concept of ABSTRACTION:
11.1 The Concept of Abstraction
Lecture 9 Concepts of Programming Languages
Abstract Data Types and Encapsulation Concepts
Introduction to Data Structure
Languages and Compilers (SProg og Oversættere)
11.1 The Concept of Abstraction
Lecture 9 Concepts of Programming Languages
Chapter 11 Abstraction - The concept of abstraction is fundamental in
Presentation transcript:

Modularity and Object-Oriented Programming John Mitchell CS 242 Reading: Chapter 10 and parts of Chapter 9

Topics uModular program development Step-wise refinement Interface, specification, and implementation uLanguage support for modularity Procedural abstraction Abstract data types –Representation independence –Datatype induction Packages and modules Generic abstractions –Functions and modules with type parameters

Stepwise Refinement uWirth, 1971 “… program... gradually developed in a sequence of refinement steps” In each step, instructions … are decomposed into more detailed instructions. uHistorical reading on web (CS242 Reading page) N. Wirth, Program development by stepwise refinement, Communications of the ACM, 1971 D. Parnas, On the criteria to be used in decomposing systems into modules, Comm ACM, 1972 Both ACM Classics of the Month

Dijkstra’s Example (1969) begin print first 1000 primes end begin variable table p fill table p with first 1000 primes print table p end begin int array p[1:1000] make for k from 1 to 1000 p[k] equal to k-th prime print p[k] for k from 1 to 1000 end

Program Structure Main Program Sub-program

Data Refinement uWirth, 1971 again: 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

Example uFor level 2, represent account balance by integer variable uFor level 3, need to maintain list of past transactions Bank Transactions DepositWithdrawPrint Statement Print transaction history

Modular program design uTop-down design Begin with main tasks, successively refine uBottom-up design Implement basic concepts, then combine uPrototyping Build coarse approximation of entire system Successively add functionality

Modularity: Basic Concepts uComponent Meaningful program unit –Function, data structure, module, … uInterface Types and operations defined within a component that are visible outside the component uSpecification Intended behavior of component, expressed as property observable through interface uImplementation Data structures and functions inside component

Example: Function Component uComponent Function to compute square root uInterface float sqroot (float x) uSpecification If x>1, then sqrt(x)*sqrt(x)  x. uImplementation float 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; }

Example: Data Type uComponent Priority queue: data structure that returns elements in order of decreasing priority uInterface Type pq Operations empty : pq insert : elt * pq  pq deletemax : pq  elt * pq uSpecification Insert add to set of stored elements Deletemax returns max elt and pq of remaining elts

Heap sort using library data structure uPriority queue: structure with three operations empty : pq insert : elt * pq  pq deletemax : pq  elt * pq uAlgorithm using priority queue (heap sort) begin empty pq s insert each element from array into s remove elements in decreasing order and place in array end This gives us an O(n log n) sorting algorithm (see HW)

Language support for info hiding uProcedural abstraction Hide functionality in procedure or function uData abstraction Hide decision about representation of data structure and implementation of operations Example: priority queue can be binary search tree or partially-sorted array In procedural languages, refine a procedure or data type by rewriting it. Incremental reuse later with objects.

Abstract Data Types uProminent language development of 1970’s uMain ideas: Separate interface from implementation –Example: Sets have empty, insert, union, is_member?, … Sets implemented as … linked list … Use type checking to enforce separation –Client program only has access to operations in interface –Implementation encapsulated inside ADT construct

Modules uGeneral construct for information hiding uTwo parts Interface: A set of names and their types Implementation: Declaration for every entry in the interface Additional declarations that are hidden uExamples: Modula modules, Ada packages, ML structures,...

Modules and Data Abstraction module Set interface type set val empty : set fun insert : elt * set -> set fun union : set * set -> set fun isMember : elt * set -> bool implementation type set = elt list val empty = nil fun insert(x, elts) =... fun union(…) = end Set uCan define ADT Private type Public operations uMore general Several related types and operations uSome languages Separate interface and implementation One interface can have multiple implementations

Generic Abstractions uParameterize modules by types, other modules uCreate general implementations Can be instantiated in many ways uLanguage examples: Ada generic packages, C++ templates, ML functors, … ML geometry modules in course reader C++ Standard Template Library (STL) provides extensive examples

C++ Templates uType parameterization mechanism template … indicates type parameter T C++ has class templates and function templates uInstantiation 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 type

Example (discussed in earlier lecture) uMonomorphic swap function void swap(int& x, int& y){ int tmp = x; x = y; y = tmp; } uPolymorphic function template template void swap(T& x, T& y){ T tmp = x; x = y; y = tmp; } uCall like ordinary function float a, b; … ; swap(a,b); …

Standard Template Library for C++ uMany generic abstractions Polymorphic abstract types and operations uUseful for many purposes Excellent example of generic programming uEfficient running time (but not always space) uWritten in C++ Uses template mechanism and overloading Does not rely on objects – No virtual functions Architect: Alex Stepanov

Main entities in STL uContainer: Collection of typed objects Examples: array, list, associative dictionary,... uIterator: Generalization of pointer or address uAlgorithm uAdapter: Convert from one form to another Example: produce iterator from updatable container uFunction object: Form of closure (“by hand”) uAllocator: encapsulation of a memory pool Example: GC memory, ref count memory,...

Example of STL approach uFunction to merge two sorted lists merge : range(s)  range(t)  comparison(u)  range(u) This is conceptually right, but not STL syntax. uBasic concepts used range(s) - ordered “list” of elements of type s, given by pointers to first and last elements comparison(u) - boolean-valued function on type u subtyping - s and t must be subtypes of u

How merge appears in STL uRanges represented by iterators iterator is generalization of pointer supports ++ (move to next element) uComparison operator is object of class Compare uPolymorphism expressed using template template < class InputIterator1, class InputIterator2, class OutputIterator, class Compare > OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator1 last2, OutputIterator result, Compare comp)

Comparing STL with other libraries uC: qsort( (void*)v, N, sizeof(v[0]), compare_int ); uC++, using raw C arrays: int v[N]; sort( v, v+N ); uC++, using a vector class: vector v(N); sort( v.begin(), v.end() );

Efficiency of STL uRunning time for sort N = 50000N = C C++ (raw arrays) C++ (vector class) uMain point Generic abstractions can be convenient and efficient ! But watch out for code size if using C++ templates…

Boost Lambda Library uC++ library providing lambda expressions uExample for_each(a.begin(), a.end(), std::cout << _1 << ' '); uFunction expression Function arguments _1, _2, _3, …, _9 Call using usual syntax (std::cout << _1 << ' ')(5) –Too many arguments – OK –Too few arguments – Compile-time error Implementation uses overloading –cout << _1 is a function expression because << is overloaded so that if one operand is a function expression, the result is a function expression function expression

Object-oriented programming uPrimary object-oriented language concepts dynamic lookup encapsulation inheritance subtyping uProgram organization Work queue, geometry program, design patterns uComparison Objects as closures?

Objects uAn object consists of hidden data instance variables, also called member data hidden functions also possible public operations methods or member functions can also have public variables in some languages uObject-oriented program: Send messages to objects hidden data method 1 msg 1... method n msg n

What’s interesting about this? uUniversal encapsulation construct Data structure File system Database Window Integer uMetaphor usefully ambiguous sequential or concurrent computation distributed, sync. or async. communication

Object-Orientation uProgramming methodology organize concepts into objects and classes build extensible systems uLanguage concepts dynamic lookup encapsulation subtyping allows extensions of concepts inheritance allows reuse of implementation

Dynamic Lookup u In object-oriented programming, object  message (arguments) code depends on object and message uIn conventional programming, operation (operands) meaning of operation is always the same Fundamental difference between abstract data types and objects

Example uAdd two numbers x  add (y) different add if x is integer, complex uConventional programming add (x, y) function add has fixed meaning Very important distinction: Overloading is resolved at compile time, Dynamic lookup at run time

Language concepts u“dynamic lookup” different code for different object integer “+” different from real “+” uencapsulation usubtyping uinheritance

Encapsulation uBuilder of a concept has detailed view uUser of a concept has “abstract” view uEncapsulation separates these two views Implementation code: operate on representation Client code: operate by applying fixed set of operations provided by implementer of abstraction message Object

Comparison with Abstract Data Types uTraditional (non-OO) approach to encapsulation is through abstract data types uAdvantage Separate interface from implementation uDisadvantage Not extensible in the way that OOP is We will look at ADT’s example to see what problem is Better: some HW involving C++ classes w/o virt fctn

Abstract Data Types uGuarantee invariants of data structure only functions of the data type have access to the internal representation of data uLimited “reuse” Cannot apply queue code to pqueue, except by explicit parameterization, even though signatures identical Cannot form list of points, colored points uData abstraction is important part of OOP, innovation is that it occurs in an extensible form

Language concepts u“Dynamic lookup” different code for different object integer “+” different from real “+” uEncapsulation Implementer of a concept has detailed view User has “abstract” view Encapsulation separates these two views uSubtyping uInheritance

Subtyping and Inheritance uInterface The external view of an object uSubtyping Relation between interfaces uImplementation The internal representation of an object uInheritance Relation between implementations

Object Interfaces uInterface The messages understood by an object uExample: point x-coord : returns x-coordinate of a point y-coord : returns y-coordinate of a point move : method for changing location uThe interface of an object is its type.

Subtyping uIf interface A contains all of interface B, then A objects can also be used B objects. uColored_point interface contains Point Colored_point is a subtype of Point Point x-coord y-coord move Colored_point x-coord y-coord color move change_color

Inheritance uImplementation mechanism uNew objects may be defined by reusing implementations of other objects

Example class Point private float x, y public point move (float dx, float dy); class Colored_point private float x, y; color c public point move(float dx, float dy); point change_color(color newc); uSubtyping Colored points can be used in place of points Property used by client program uInheritance Colored points can be implemented by resuing point implementation Propetry used by implementor of classes

OO Program Structure uGroup data and functions uClass Defines behavior of all objects that are instances of the class uSubtyping Place similar data in related classes uInheritance Avoid reimplementing functions that are already defined

Example: Geometry Library uDefine general concept shape uImplement two shapes: circle, rectangle uFunctions on implemented shapes center, move, rotate, print uAnticipate additions to library

Shapes uInterface of every shape must include center, move, rotate, print uDifferent kinds of shapes are implemented differently Square: four points, representing corners Circle: center point and radius

Subtype hierarchy Shape CircleRectangle uGeneral interface defined in the shape class uImplementations defined in circle, rectangle uExtend hierarchy with additional shapes

Code placed in classes uDynamic lookup circle  move(x,y) calls function c_move uConventional organization Place c_move, r_move in move function centermoverotateprint Circlec_centerc_movec_rotatec_print Rectangler_centerr_mover_rotater_print

Example use: Processing Loop Remove shape from work queue Perform action Control loop does not know the type of each shape

Subtyping differs from inheritance Collection Set Sorted Set Indexed Array Dictionary String Subtyping Inheritance

Design Patterns uClasses and objects are useful organizing concepts uCulture of design patterns has developed around object-oriented programming Shows value of OOP for program organization and problem solving

What is a design pattern? uGeneral solution that has developed from repeatedly addressing similar problems. uExample: singleton Restrict programs so that only one instance of a class can be created Singleton design pattern provides standard solution uNot a class template Using most patterns will require some thought Pattern is meant to capture experience in useful form Standard reference: Gamma, Helm, Johnson, Vlissides

OOP in Conventional Language uRecords provide “dynamic lookup” uScoping provides another form of encapsulation Try object-oriented programming in ML. Will it work? Let’s see what’s fundamental to OOP

Dynamic Lookup (again) receiver  operation (arguments) code depends on receiver and operation This is may be achieved in conventional languages using record with function components

Stacks as closures fun create_stack(x) = let val store = ref [x] in {push = fn (y) => store := y::(!store), pop = fn () => case !store of nil => raise Empty | y::m => (store := m; y) } end; val stk = create_stack(1); stk = {pop=fn,push=fn} : {pop:unit -> int, push:int -> unit}

Does this work ??? uDepends on what you mean by “work” uProvides encapsulation of private data dynamic lookup uBut cannot substitute extended stacks for stacks only weak form of inheritance –can add new operations to stack –not mutually recursive with old operations

Varieties of OO languages uclass-based languages behavior of object determined by its class uobject-based objects defined directly umulti-methods operation depends on all operands This course: class-based languages

History uSimula 1960’s Object concept used in simulation uSmalltalk 1970’s Object-oriented design, systems uC ’s Adapted Simula ideas to C uJava 1990’s Distributed programming, internet

Next lectures uSimula and Smalltalk uC++ uJava

Summary uObject-oriented design uPrimary object-oriented language concepts dynamic lookup encapsulation inheritance subtyping uProgram organization Work queue, geometry program, design patterns uComparison Objects as closures?