Program Design, Design Patterns, Type Theory, and other buzzwords. - PowerPoint PPT Presentation

1 / 52
About This Presentation
Title:

Program Design, Design Patterns, Type Theory, and other buzzwords.

Description:

Why is this Bad? The types don't hide anything! Unanticipated errors can happen ... The Sky is the Limit! The type system becomes a programming language of its own ... – PowerPoint PPT presentation

Number of Views:76
Avg rating:3.0/5.0
Slides: 53
Provided by: amras9
Category:
Tags: blue | buzzwords | design | is | patterns | program | sky | the | theory | type | why

less

Transcript and Presenter's Notes

Title: Program Design, Design Patterns, Type Theory, and other buzzwords.


1
Program Design,Design Patterns,Type Theory,and
other buzzwords.
  • Amr Sabry
  • ???? ????
  • Indiana University

2
Playing Music
3
Building Structures
4
Programming
  • (define fact
  • (lambda (n)
  • (if (zero? n)
  • 1
  • ( n (fact (sub1 n))))))

5
Levels of Abstraction
  • As programmers we must deal with different levels
    of abstraction
  • Write little pieces of code, encapsulate them by
    hiding the irrelevant details, and describing
    their behavior in concise terms.
  • Use these encapsulations as building blocks for
    the next layers of abstraction, etc.

6
Outline
  • Part I
  • Abstraction and Reuse
  • Part II
  • Abstraction and Safety

7
Part I
  • Abstraction and Reuse

8
Reuse
  • Do we want to reuse code? YES!!!
  • We earlier said
  • Write little pieces of code, encapsulate
    them by hiding the irrelevant details, and
    describing their behavior in concise terms.
  • What is irrelevant depends on how the code will
    be used!!!

9
Which is an abstraction of a human?
10
Reuse (unanticipated)
  • If we choose one particular abstraction, then we
    essentially rule out some future uses of the
    software.
  • Unfortunately people like to modify software
    after the fact in unpredictable ways!

11
Architecture and Design Patterns
  • Christopher Alexander
  • Design of a building is tied to the anticipated
    uses and must be flexible to accommodate other
    emerging uses.
  • The uses are captured in pattern languages and
    all buildings are the result of applying sets of
    rules (or pattern languages - sets of related
    patterns)
  • Alexander's Patterns
  • a pattern is a formalized instruction that says
    "if you encounter this problem, then solve it
    like that"
  • patterns are the means to an end or rules of
    thumb
  • patterns are used in combination, with
    cross-referencing, enabling decisions to be made
    in a reasonable order
  • Software Design Patterns
  • "These patterns solve specific design problems
    ...  make object-oriented designs more flexible,
    elegant and ultimately reusable ...  basing new
    designs on prior experience ... without having to
    rediscover them ... (Gamma et al. 1995) 

12
Warning!
  • Lots of details to follow!

13
A Design Problem
  • McSabry food chain needs a program to keep track
    of the food items it sells.
  • Initially, McSabry will focus on ice cream,
    hotdogs, and pizza.
  • For each food item, we will need to keep track of
    its cost and selling price so that we can compute
    the profit from sales.

14
An Initial Java Design
FoodItem
Cost Price
IceCream
Hotdog
Pizza
15
Java Implementation
  • abstract class FoodItem
  • abstract int cost ()
  • abstract int price()
  • class HotDog
  • class Pizza
  • class IceCream extends FoodItem
  • int cost ()
  • return 1
  • int price ()
  • return 5

16
Sales and Profit
  • class Profit
  • int profit (FoodItem sales)
  • int totcost 0 int totprice 0
  • for (int i0 iltsales.length i)
  • totcost salesi.cost()
  • totprice salesi.price()
  • return totprice totcost

17
McSabry expands
  • McSabry decides to add Vegetables to its food
    items.
  • We need to modify the design and the program!

18
Updated Design
FoodItem
Cost Price
Vegetables
IceCream
Hotdog
Pizza
19
Updated Implementation
  • class Vegetables extends FoodItem
  • int cost () return 2
  • int price () return 4
  • Code already written does NOT have to change at
    all!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

20
FDA
  • Unfortunately McSabry discovered recently that
    the FDA requires that the company reports the
    number of calories in every food item.
  • Need to modify the design and program again!

21
Updated Design
FoodItem
Cost Price Calories
Vegetables
IceCream
Hotdog
Pizza
22
Updated Implementation
  • Oops!
  • Must go back and change EVERY class that we have
    written.
  • Scale this to millions of line of code
  • Lets revise our original design

23
The problem
  • We did not anticipate reuse in one dimension.
  • How could we modify the design to accommodate
    growth not only in new food items but also in new
    operations on food items.
  • Solution the Visitor Pattern.

24
Visitor Pattern
FoodItem
accept
Vegetables
IceCream
Hotdog
Pizza
visitIceCream visitHotDog visitPizza visitVegetabl
es
FoodVis
CostVis
PriceVis
CaloriesVis
25
Implementation
  • class IceCream extends
  • FoodItem
  • int accept (FoodVis fv)
  • return fv.visitIceCream()
  • class PriceVis extends
  • FoodVis
  • int visitIceCream ()
  • return 5
  • int visitVegetables ()
  • return 4

26
Extensible Reusable Code
  • Possible to add new operations on food items
    without changing any existing code.
  • With another small modification, it is possible
    to add more food items without changing any
    existing code.

27
Summary of Part I
  • Before we can abstract we must decide what is
    relevant and what is irrelevant. Need design
    experience, patterns, etc.
  • Most CS courses teach abstraction. Focus on reuse
    comes in class that focus on programming in the
    large, software engineering, and OO design.

28
Part II
  • Abstraction and Safety

29
Programming with Abstractions
  • Assuming we have already decided what is relevant
    and what is irrelevant, how do really hide the
    irrelevant details and be sure they will not
    somehow leak out?

30
Types
  • Types are a syntactic discipline for enforcing
    levels of abstractions Reynolds
  • Not comments
  • Part of the programming language
  • Checked and enforced by the compiler

31
Interfaces (from Java 2)
  • public interface Collection
  • boolean add (Object o)
  • bollean addAll (Collection c)
  • void clear ()
  • boolean contains (Object o)
  • boolean containsAll (Collection c)
  • boolean equals (Object o)
  • int hashCode ()
  • boolean isEmpty ()
  • Iterator iterator ()
  • boolean remove (Object o)
  • boolean removeAll (Collection c)
  • boolean retainAll (Collection c)
  • int size ()
  • Object toArray ()
  • Object toArray (Object a)

32
Type Safety
  • Informal
  • If the compiler determines that some expression
    has type T, then it will have type T at runtime.
  • No unanticipated errors.
  • Bad example
  • Compiler determines that e has type int
  • Hence ok to write 1e
  • But e evaluates to an array of booleans.

33
Example in C (I)
  • From Intensional Equality for Continuations by
    Andrew Appel
  • A function in a high-level programming language
    is just the address of an instruction at the
    machine level. In C one can mix high-level
    functions and unsigned numbers!!!

34
Warning!
  • Lots of details to follow!

35
Example in C (II)
  • cMain (int ac, charav)
  • int i,j
  • (void) srandom (atoi (av1))
  • for (i0 i lt 10000000 i)
  • j quickroot (random())
  • exit(0)
  • eMain()
  • unsigned mycaller 0x81c3e008,0x9010001f

36
Example in C (III)
  • int quickroot (int i)
  • static x 0
  • if (x) return cbrt (i)
  • x1
  • unsigned p, q, caller
  • union unsigned z
  • unsigned (f)()
  • u
  • u.z mycaller
  • caller u.f()
  • if (caller lt (unsigned)main
  • caller gt (unsigned)main
  • (unsigned)eMain -
  • (unsigned)cMain)
  • return quickroot(i)
  • exit(0)

37
Whats going on?
  • Layout
  • If main cMain then do nothing
  • If main is anything else then call the real cbrt
    function

quickroot
main
38
Why is this Bad?
  • The types dont hide anything!
  • Unanticipated errors can happen
  • Evaluation can even proceed with nonsense
  • No abstraction

39
Why is it REALLY Bad?
  • From Securing Java, John Wiley Sons, Inc.
  • The Java language is designed to enforce type
    safety. This means that programs are prevented
    from accessing memory in inappropriate ways
    Type safety means that a program cannot perform
    an operation on an object unless that operation
    is valid for that object.
  • Type safety is the most essential element of
    Javas security In our experience, every type
    safety violation has created an opportunity for
    an untrusted applet to break out of Javas
    security restrictions.

40
Safety with a Straightjacket
  • Pascal was safe (almost!)
  • Pascals type system was very limited (a function
    that sorts an array of ints cannot sort an array
    of floats)
  • Need expressive type system that is safe.

Here lies Pascal A Language Chocked by its
Type System
41
An Expressive Safe Type System Haskell
  • Lookup (Eq a) gt
  • a -gt (a,b) -gt Maybe b
  • lookup key Nothing
  • lookup key ((x,y)xys)
  • key x Just y
  • otherwise lookup key ys
  • There are even more advanced type systems but
    they are not part of mainstream programming
    languages
  • Hot research topic with new proposals emerging
    every year

42
Haskell primitive types
  • Based on tutorial on haskell.org
  • 5 Integer
  • a Char
  • inc Integer -gt Integer
  • inc n n1
  • 1,2,3 Integer
  • (b,4) (Char, Integer)

43
Polymorphic Types
  • length forall a. a -gt Integer
  • length 0
  • length (xxs) 1 length xs
  • length 1,2,3 ? 3
  • length a, b, c ? 3
  • length 1,5, 2,5, 3,5 ? 3

44
User-Defined Types
  • data Bool False True
  • data Color Red Green Blue Indigo
  • data Point a Pt a a
  • Pt 2.0 3.0 Point Float
  • Pt a b Point Char
  • Pt True False Point Bool
  • Pt a 1 TYPE ERROR

45
Recursive Types
  • data Tree a Leaf a Branch (Tree a) (Tree a)
  • Branch Tree a -gt Tree a -gt Tree a
  • Leaf a -gt Tree a
  • fringe Tree a -gt a
  • fringe (Leaf x) x
  • fringe (Branch left right) fringe left
    fringe right

46
Type Classes
  • class Eq a where
  • () a -gt a -gt Bool
  • instance Eq Integer where
  • x y x integerEq y
  • instance Eq Float where
  • x y x floatEq y
  • instance (Eq a) gt Eq (Tree a) where
  • Leaf a Leaf b
    a b
  • (Branch l1 r1) (Branch l2 r2) (l1
    l2) (r1 r2)
  • _ _
    False

47
Modules
  • module Tree (Tree(Leaf,Branch), fringe) where
  • data Tree a Leaf a Branch (Tree a) (Tree
    a)
  • fringe Tree a -gt a
  • fringe (Leaf x) x
  • fringe (Branch l r) fringe l fringe r
  • module Main (main) where
  • import Tree( Tree(Leaf,Branch), fringe)
  • main print (fringe (Branch (Leaf 1) (Leaf 2)))

48
Existential Types
  • module TreeADT (Tree, leaf, branch, cell, left,
    right, isLeaf) where
  • -- We know there exists a type Tree but
    representation is HIDDEN
  • data Tree a Leaf a Branch (Tree a) (Tree a)
  • leaf Leaf
  • branch Branch
  • cell (Leaf a) a
  • left (Branch l r) l
  • right (Branch l r) r
  • isLeaf (Leaf _) True
  • isLeaf _ False

49
Monads Memory Encapsulation
  • new forall a. a -gt ST s (Ref s a)
  • read forall a. Ref s a -gt ST s a
  • write forall a. Ref s a -gt a -gt ST s ()
  • runST forall a. (forall s. ST s a) -gt a
  • If (runST e) typechecks then
  • e does not use any memory allocated from the
    outside
  • The memory allocated by e is not visible on the
    outside.
  • Can evaluate e on a local processor
  • Can immediately reclaim the memory used by e
  • etc

50
And so on
  • Parametricity Theorem for Haskell (informal)
  • If a program typechecks then it is likely to be
    correct!!!!!!
  • Intuition Assume I tell you a term has type
    forall a. a -gt a, what could it be?
  • The only sensible term of this type is the
    function f defined as
  • f x x

51
The Sky is the Limit!
  • The type system becomes a programming language of
    its own
  • Programs at the type level are proofs about the
    regular programs
  • Proof-Carrying Code An emerging industry!

52
Conclusion
  • Abstraction is at the heart of CS
  • Finding the right abstractions is hard
    engineering aspect of Programming
  • Expressing and enforcing rich abstractions
    theoretical foundations of Programming Languages
Write a Comment
User Comments (0)
About PowerShow.com