CptS 355 Programming Language Design - PowerPoint PPT Presentation

1 / 60
About This Presentation
Title:

CptS 355 Programming Language Design

Description:

CptS 355. Programming Language Design. Roger Ray. WSU Vancouver, Spring 2001. OOP 1 ... Animal *archie = new Animal (1, 2); // a cockroach ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 61
Provided by: roge2
Category:

less

Transcript and Presenter's Notes

Title: CptS 355 Programming Language Design


1
CptS 355Programming Language Design
OOP 1
  • Roger Ray
  • WSU Vancouver, Spring 2001

2
This Week
  • Compilers wrap-up
  • production compiler discussion
  • Object-Oriented Languages
  • reading 10, 11 (skim 11.4-11.8, study 11.9, skip
    11.10-11.12)
  • lab
  • Presentation

3
OOP Context
4
Three Convergent Software Challenges
surprising
Simulation
Maintenance
Kids
1970's
1985
1967
Simula
Smalltalk
C
5
The Convergence ...
Organize software as a simulated physical system!
  • interacting
  • independent
  • objects

6
Structure of an OOP Program
some object
interaction
another object
and another object
yet another object
  • Each object has
  • a unique identity
  • a definite type
  • hidden and visible parts
  • hidden and visible behaviors
  • Interactions are limited to visible
  • parts and behaviors
  • Example objects with behaviors
  • a Stack push, pop
  • a File open, getInfo
  • a Canvas drawLine, clear
  • a CommandLine getArg
  • an Integer , -,

7
Key OOP Technique ...
Organize objects into hierarchical classes
  • Taxonomy
  • Vehicles
  • Data Structures

Vehicle
more general parts and behaviors
Car
Truck
Sedan
Station wagon
SUV
more specific parts and behaviors
2 door
4 door
Stack
Queue
Heap
8
OOP Example
Animal
Mammal
Canine
Fido
Rover
Keiko
9
OOP Terminology
class - a type- a set
Animal
subclass - a subtype - a proper subset - a
derived class - a child class
Mammal
Canine
  • superclass
  • - an enclosing class
  • a base class
  • a parent class

Fido
Rover
instance - an object - an individual
Keiko
  • part
  • - an attribute
  • - some data
  • a field
  • a (data) member
  • method
  • a behavior- some code
  • a procedure
  • - a member function

10
Classes and Parts Are Defined Together
  • an Animal
  • has a height and length
  • a Mammal is an Animal
  • also has a color
  • a Canine is a Mammal
  • also has a name

struct Animal double height, length //
cm struct Mammal Animal int color //
1 brown, ... struct Canine Mammal
char name // e.g. "Fido" // note the
The parts accumulate
aka "members"
  • Notes
  • Canine is subclass of Mammal and Animal
  • Mammal is subclass of Animal
  • Animal is subclass of ?

11
Each Class Must Have a Constructor
  • Creatingnewinstances
  • Theconstructorcode
  • The creationeffect

Animal archie new Animal (1, 2) // a
cockroach Mammal keiko new Mammal (6, 1e5,
3e5) // a whale
struct Animal double height, length Animal
(double h, double l) height h // same as
this-gtheight l length l struct
Mammal Animal int color Mammal (int c,
double h, double l) Animal (h, l) color
c
height 1, length 2
archie
keiko
height 1e5, length 3e5, color 6
12
Multiple Constructors are Allowed
  • Two waysto make anew Canine
  • Exampleusage

struct Canine Mammal char name Canine
(char n, int c, double h, double l) Mammal (c,
h, l) name n Canine (char n)
Mammal (1, 40.0, 72.0) name n
Canine x new Canine ("Fido")
x
height 40, length 72 color 1, name "Fido"
x new Canine ("Rover")
height 40, length 72 color 1, name "Fido"
x
height 40, length 72 color 1, name "Rover"
13
Inherit Parts ...
struct Animal double height, length //
cm struct Mammal Animal int color // 1
brown, ... struct Canine Mammal char
name // e.g. "Fido"
Canine x new Canine ("Fido") printf ("x's
color d\n", x-gtcolor) printf ("x's size
g\n", x-gtheight x-gtlength)
x is an Animal x is a Mammal x is a Canine
Animal parts
x
Mammal parts
Canine parts
14
Instances Can Be Shared
Canine x new Canine ("Fido") Canine y
new Canine ("Rover") Canine z printf ("x's
name s\n", x-gtname) printf ("y's name
s\n", y-gtname) printf ("z's name s\n",
z-gtname) // NO z y x y y-gtname
"Marmaduke" printf ("x's name s\n",
x-gtname) printf ("y's name s\n",
y-gtname) printf ("z's name s\n", z-gtname) //
OK
Draw and update diagrams to show what is
happening!
15
Can't Contradict Declarations
Mammal k new Mammal (1, 1e5, 3e5) Canine x
new Canine ("Fido") printf ("k's name
s\n", k-gtname) // NO
k is an Animal k is a Mammal
Animal parts
k
Mammal parts
x is an Animal x is a Mammal x is a Canine
Animal parts
x
Mammal parts
Canine parts
k x // OK x k // NO
x is always a Mammal k might not be a Canine
16
Inherit Behavior ...
struct Animal ... virtual void display ()
printf ("Animal (g, g)", height,
length) struct Mammal Animal
... virtual void display () printf
("Mammal (d, g, g)", color, height,
length) struct Canine Mammal ...
What is going on?
Animal a, m, c a new Animal (100, 200) m
new Mammal (1, 1e5, 3e5) c new Canine
("Rover") printf ("a ") a-gtdisplay ()
printf ("\n") printf ("m ") m-gtdisplay ()
printf ("\n") printf ("c ") c-gtdisplay ()
printf ("\n")
g -o example example.cpp example a Animal
(100, 200) m Mammal (1, 100, 200) c Mammal
(1, 100, 200)
key term "override"
17
Reuse Behavior ...
struct Animal ... struct Mammal Animal
... struct Canine Mammal virtual
void display () printf ("Canine (s) ... ",
name) Mammaldisplay ()
What is going on?
Animal a, m, c a new Animal (100, 200) m
new Mammal (1, 1e5, 3e5) c new Canine
("Rover") printf ("a ") a-gtdisplay ()
printf ("\n") printf ("m ") m-gtdisplay ()
printf ("\n") printf ("c ") c-gtdisplay ()
printf ("\n")
g -o example example.cpp example a Animal
(100, 200) m Mammal (1, 100, 200) c Canine
(Rover) ... Mammal (1, 100, 200)
18
Runtime Issues
19
1. Instance Layout?
instance-gtmethod (args ...)
superClass method (args ...)
  • find most specific method implementation in fixed
    time
  • invoke superclass methods on request

issues
  • layout parts methods at compile time
  • determine actual class at runtime

solution
aka "dynamic method binding"
20
... Runtime Structures Do The Job
class info
struct Animal double height, length virtual
void display () ... struct Mammal
Animal int color virtual void display ()
... struct Canine Mammal char
name
Animal ?
0
display code
Mammal ?
superclass
display code
instance info
Canine ?
superclass
display code
x ?
class
height
length
color
name
(x-gtheight) (x-gtclass-gtdisplay) (x)
Mammal x new Canine ( ... ) ... x-gtheight
... ... x-gtdisplay () ...
21
2. Storage Reclamation?
struct Table Entry e int lookup (char
key, int code ... Table (int n) e
new Entryn ... Table t new Table
(100) t-gtlookup ("abc", 0) ... // t no longer
needed ...
  • how reclaim storage?
  • reclamation may require recursive logic

issues
"destructors"
solution
22
... Destructors Do The Job
struct Table Entry e int lookup (char
key, int code ... Table (int n) e
new Entryn ... Table () delete
e Table t new Table (100) t-gtlookup
("abc", 0) delete t
note the tilde
23
3. Storage Ownership?
  • who reclaims storage?

issue
solutions
common practice
explicit delete
  • Few new's
  • Storage ownership clear
  • Allocator reclaiming is good practice

1. classic style (e.g. C)
implicit garbagecollection
  • Many new's
  • Storage ownership unclear
  • Automatic reclaiming

2. new style (e.g. Java)
24
OOP Benefit
25
OOP Benefit
Modify software behavior without modifying
software sources
  • 1. Organization
  • Objects are instances of classes
  • Classes are organized into a hierarchy

A
B
C
  • 2. Data
  • Instances have parts
  • Subclasses may add new parts

...
D
  • 3. Behavior
  • Subclasses may add or override methods
  • Most specific method implementation used
  • Subclass method can invoke superclass code

instance-gtmethod (args ...)
26
OOP Examples
  • Calc compiler
  • general game player
  • data structures

27
1. Compiler Hard to Add New Nodes
non-OOP data type
non-OOP code gen
enum Kind Semi, Print, Calc, Number struct
Node Kind kind int where Node x,
y union double value char
opcode void gen () Node (Kind kind,
Node x0, ...) ... Node (double value)
...
void Nodegen () switch (kind) case
Calc // x opcode y x-gtgen () y-gtgen
() printf ("s\n", opcode) break case
Number // value printf ("push\tg\n",
value) break case Print // x x-gtgen
() printf ("sys\t9\n") break ...
// switch
28
Solution Inheritance
OOP data type
tree.h
OOP code gen
gen.cpp
struct Node int where virtual void gen
() Node () this-gtwhere yywhere struct
Print Node Node x virtual void gen
() Print (Node x) this-gtx x struct
Semi Node Node x, y virtual void gen
() Semi (Node x, Node y) this-gtx
x this-gty y struct Number Node
double value virtual void gen () Number
(double value) this-gtvalue value struct
Calc Semi char opcode virtual void gen
() Calc (Node x, Node y, char opcode) Semi
(x, y) this-gtopcode opcode
void Nodegen () // never called assert
(0) void Calcgen () // x opcode y x-gtgen
() y-gtgen () printf ("s\n",
opcode) void Numbergen () //
value printf ("push\tg\n", value) void
Printgen () // x x-gtgen () printf
("sys\t9\n") void Semigen () // x
y x-gtgen () y-gtgen ()
29
2. General Game Player
  • Example two-person board games
  • chess
  • checkers
  • tic-tac-toe
  • ...
  • These games have common elements
  • one player wins
  • alternating moves
  • perfect information
  • deterministic
  • Can we write a general game player?

30
Use "Look Ahead" For Selecting Next Move
  • Full look ahead approach
  • call one player "max", the other "min"
  • assign appropriate utility to terminal positions
  • generate all possibilities from current position
  • max chooses move that leads to max terminals
  • min prefers min paths
  • More sophisticated approaches
  • mini-max with cut-off
  • alpha-beta pruning with cut-off

31
Design of a General Game Player
game.h
struct List Move move List next struct
Board virtual int isTerminalPosition
() virtual int terminalUtility () virtual List
possibleMoves () virtual void makeMove (Move
move) virtual void unmakeMove (Move
move) Board () struct Move Move ()
struct Logic virtual Move bestMove
(Board board) Logic ()
ttt.h
include ltgame.hgt struct TicBoard Board int
square 9 ... member functions overrides
... struct TicMove Move int mark
AI experts
game experts
main.cpp
include ltgame.hgt include ltttt.hgt int main
(...) Board board new TicBoard () Logic
logic new AlphaBetaLogic () while (... game
not over ...) ... display board ... ... get and
make human move ... Move move logic.bestMove
(board) board.makeMove (move)
alpha.cpp
include ltgame.hgt struct AlphaBetaLogic Logic
... member function overrides ...
g -c alpha.cpp ... archive in the game
library ...
g -c main.cpp g -o ttt main.o -lgame
32
Sidebar Alpha-Beta vs. Humans
From Artificial Intelligence A Modern
Approach Russel Norvig (1995)
33
3. Data Types
  • Classical data types canbe organized into
    ahierarchy
  • Benefits
  • helps organize function
  • encourages reuse
  • permits further specialization

34
4. GUI Elements
  • Let's design a class hierarchy for GUI
    programming ...

35
Key Technique "Frameworks"
  • Library-based programming
  • Framework-based programming

your code
framework
class 1
class 2
calls to library routines
class 3
subclasses and overrides
lib 4
lib 2
lib 3
library 1
your code
key term "polymorphism"
36
Encapsulation
37
1. Privacy
  • provide hidden parts and methods
  • separate clients from trusted other classes

problem
table.h
struct Entry int hash // the hash code
for the key Entry next // next entry or the
sentinel char name // the lookup
key int code // an arbitrary code Info
info // current info for this name // A
symbol table with some member functions struct
Table Entry entry // an array of
entries int size // actual size of the
array Entry lookup (char name, int
code) void dump () Table (int size
101)
should be private!
38
... Replace "struct" With "class"
  • Mark member fields and functions as "public" or
    "private"
  • Add a "friend" class if private should be public
    to that special class

table.h
class Entry int hash // the hash code for
the key Entry next // next entry or the
sentinel friend class Table public char
name // the lookup key int code // an
arbitrary code Info info // current info
for this name // A symbol table with some
member functions class Table Entry entry
// an array of entries int size // actual size
of the array public Entry lookup (char
name, int code) void dump () Table (int
size 101)
private to everyone but Table
private thingscan only be used inside member
functions of this class or of the friend
private to everyone!
struct A B ... ?
39
... A Newer and Clearer Style
  • Mark member fields and functions as "public" or
    "private"
  • Add access methods ("get" and "set", as needed)
  • Add a "friend" class if private should be public
    to that special class

class Entry public int code // an
arbitrary code Info info // current info
for this name char getName () // the
lookup key private char name // the
lookup key int hash // the hash code for the
key Entry next // next entry or the
sentinel friend class Table // A symbol
table with some member functions class Table
public Entry lookup (char name, int
code) void dump () Table (int size
101) private Entry entry // an array of
entries int size // actual size of the
array
table.h
explicit private, plus access methods and friends
private thingscan only be used inside member
functions of this class or of the friend class
explicit private
40
2. Contracts
  • ensure subclasses implement a method

problem
"abstract" class
solution
  • superclass
  • declares a method to be "abstract"
  • prevents instance creation
  • subclass
  • implements the method
  • allows instance creation

class Animal virtual void walk (int distance)
0
class Mammal public Animal virtual void walk
(int distance) ...
other terms deferred method, pure virtual method
(C)
41
OOP Is Best Current Technique For Info Hiding
language developments for hiding information
technique
advantages
weakness
  • procedures hidden code visible persistent state
  • modules hidden persistent state one instance
  • ADT multiple instances can't reuse
    implementations can't change behavior
  • OOP all of above can reuse implementations can
    change behavior can create contracts

42
3. Modification Rights
  • Can promise to not modify content of a structure
  • add adjective "const" to a formal
  • excellent coding practice
  • Can also use "const" in definitions
  • more flexible than define's
  • still, "constant expressions" (e.g. static array
    bounds) must be int via built-in op's

int strlen (const char s) // won't change any
si
char strcpy (char s, const char t) // may
change some si
const double PI 4 atan (1, 1)
define PI 3.1415926535897932384626433832795
43
4. Separate Compilation
  • Assist construction of large systems
  • avoid massive recompilations compile only
    changed modules
  • avoid publishing sources compile and link
    with binaries
  • General approach

user
module interface (source)
implementer
user program (source)
compile
module implementation(source)
module interface(binary)
compile
user program(binary)
compile
module implementation(binary)
  • e.g. Ada
  • cf. Java
  • cf. C

link
final executable(binary)
44
5. Pre/Post Conditions
  • Help user understand how to use your routine
  • pre what your code assumes is true at start
  • post what your code claims is true at end
  • Help debug your code
  • add checking code in your implementation via
    "assert" macro

// indexOfMin Return index of min element in an
array. int indexOfMin (int a, int
n) / pre n gt 1 a0..n-1 any values in
any order post aresult lt ai for all
i0..n-1 /
foo.h
int indexOfMin (int a, int n) assert (n gt
1) ... assert (isValidResult (result, n,
a)) return result
foo.cpp
45
Advanced Techniques
46
1. How Can We Make a General List?
list.h
struct List int head List tail List (int
a, List b) head a tail b
template ltclass Tgt struct List T head List
tail List (T a, List b) head a tail
b
struct List ? head List tail List (? a,
List b) head a tail b
struct Book char title Node (char t)
title t
book.h
terms "parameterized types", "generic types",
"abstract types?"
typedef List ltBook gt BookList int main ()
BookList x Book b b new Book
("abc") x new BookList (b, 0) printf
("s", x-gthead-gttitle)
include "list.h" include "book.h" int main ()
List ltBook gt x Book b b new Book
("abc") x new List ltBook gt (b, 0) printf
("s", x-gthead-gttitle)
main.cpp
47
2. How Can All Instances Share a Value?
point.h
struct Point double x, y static int
npoints Point (double x, double y)
npoints this -gt x x this -gt y
y static const double pi 3.1415
main.cpp
include ltstdio.hgt include "point.h" int
Pointnpoints 0 int main () Point p
new Point (0, 0) printf ("npoints d\n",
Pointnpoints) printf ("pi g\n",
Pointpi)
term "class variable" and "instance variable"
48
C Dangers
49
Watch Out!
  • Only for advanced and specialized code
  • non-pointer based classes
  • non-virtual overrides
  • multiple inheritance
  • Useful, but use with care
  • protected members
  • operators
  • templates (classes and functions)
  • Many other obscure capabilities
  • pointers to members
  • virtual inheritance
  • copy constructors and references ...

50
Smalltalk
51
Smalltalk A Quick Glance
Smalltalk is ...
  • A language
  • the exemplar OOP language
  • A system
  • a complete programming system with GUI, debugger,
    etc.
  • A vision
  • how users computers should work together
  • Big
  • few concepts, but huge number of classes and
    methods

52
Smalltalk A Pure OOP Language
Everything is an object
  • All operations are method invocations
  • Everything is on heap (even stack frames)
  • Types are checked only at runtime
  • Compiler optimizes common cases

53
Smalltalk Everything is an Object
write this
x y
means this
x-gtplus (y)
class Integer public Object public Integer
plus (Integer b) ...
implemented like this
54
Smalltalk Everything is an Object
if xthen y else z
write this
(the brackets create inner procedures without
parameters, called "blocks")
means this
x-gtifThenElse (y, z)
class Boolean public Object public virtual
void ifThenElse (Block a, Block b)
0 class True public Boolean public
virtual void ifThenElse (Block a, Block b)
a() class False public Boolean public
virtual void ifThenElse (Block a, Block b)
b()
implemented like this
55
Smalltalk Everything is an Object
while x do y
write this
x-gtwhileDo (y)
means this
class Block public Object public void
whileDo (Block a) if (this()) a()
this-gtwhileDo (a) else
implemented like this
56
Smalltalk Classes
  • All primitive data types are objects
  • All OS interfaces are objects
  • Extensive set of utility classes
  • collections
  • time date
  • GUI
  • threads
  • ...

programming becomes an activity of extending
something, rather than creating from scratch
57
OOP Wrap-up
58
Defining OOP Precisely ...
Object-oriented programming is ...
  • the objective of
  • programming by assembling solutions
  • from existing components
  • without source modification

Object-oriented languages provide a technology to
achieve the objective
  • Some other OO technologies
  • Microsoft COM/OLE/ActiveX
  • CORBA
  • Unix shell

Thanks to Brad Cox, Object-Oriented
Programming An Evolutionary Approach
59
Important OOP Languages ...
Algol-60
simulation
Simula
kids, GUI
Smalltalk
C
C
Internet
Java
60
Key Points
  • OOP objective
  • assemble existing components into new systems
    without source modification
  • Key insight
  • organize software as a simulated physical system
  • Key technique
  • objects classes with inheritance
  • Things to remember
  • dynamic method binding
  • runtime issues (instance layout, constructors
    destructors)
  • framework approach, polymorphism, abstract
    classes
  • encapsulation
  • Things to learn in future
  • more C (especially ltiostream.hgt, STL, and
    exceptions)
  • then (perhaps) Java
  • OOA and UML

61
The Problem OOP Is Trying to Solve ...
Modify software behavior without modifying
software sources
fun gen t (Number (r)) ... gen t (String
(g)) ... gen t (Void) ... gen t (Add
(x, y)) ... gen t (Sub (x, y)) ...
gen t (Mul (x, y)) ... ...
  • Add behavior
  • Change behavior
  • Combine behavior

Power op
windows w/ flat buttons
windows w/ 3D buttons
filedialog
62
Specify Behavior with Methods
instance -gt method (args ...)
  • an Animal can
  • return its volume
  • display its parts
  • a Mammal can
  • return its volume
  • display its parts
  • a Canine can also
  • return its volume
  • display its parts
  • play with another Canine

Canine x new Canine ("Fido") Canine y new
Canine ("Rover") Mammal m new Mammal (1,
1e5, 3e5) x-gtdisplay () m-gtdisplay () m
y m.display () x.play (y)
. invokes a method, or gets a part
code
Note how subclasses add more behavior
63
C and Java Notes
Programmer can optimize the method lookup
  • Virtual method
  • method can be overridden in subclass
  • dynamic method lookup needed
  • in C, say "virtual" in Java say nothing
  • Non-virtual method
  • method cannot be overridden
  • static method lookup possible
  • in C say nothing, in Java, say "final"

(x-gtclass-gtvolume) (x)
Canine_volume (x)
64
Outline
  • Motivation
  • maintenance, simulation, kids
  • Techniques
  • polymorphism
  • inheritance subclasses, virtual functions
  • Implementation
  • Examples
  • Calc, game playing, GUI elements, text editor
  • Practice
  • design and implementation guidelines
  • storage management
  • templates
  • Dangers C and other monsters
  • non-pointer based classes
  • non-virtual overrides
  • Lab
Write a Comment
User Comments (0)
About PowerShow.com