OO Design and STL - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

OO Design and STL

Description:

In my undergrad OO design class, on the practice test: 'What is wrong with these ... Good to learn about if you plan to design large OO systems. Back to vectors. ... – PowerPoint PPT presentation

Number of Views:60
Avg rating:3.0/5.0
Slides: 43
Provided by: andrew45
Category:
Tags: stl | design

less

Transcript and Presenter's Notes

Title: OO Design and STL


1
OO Design (and STL)
  • CSE 399
  • Mar 19, 2008

2
Reminders
  • Homework 4 Due today
  • Exam April 2nd
  • You may bring 1 page (8.5 x 11 inches) of
    handwritten notes to the exam.

3
Today
  • OO Design
  • How to design an OO program well
  • Brief intro to design patterns
  • Standard Template Library
  • vectors, etc
  • some examples of design concepts

4
First one thing about types
  • If I write
  • x x
  • What does it mean?
  • x times x you say?
  • Always?
  • Are you sure?

5
Maybe I said
  • Maybe above that I wrote
  • typedef int x
  • .
  • Now what does this mean
  • x x
  • Declaration of an int pointer called x.
  • You cant locally tell what is a type in C.

6
Non-silly consequence
  • Silly example, but real consequences.
  • In templates need to be explicit what is a type
    sometimes
  • templateltclass Tgt void foo(int x)
  • Tx(y)
  • .
  • Is Tx a type gt declare variable y
  • Is Tx a function gt call it with y as argument

7
The rule
  • If you have a qualified (with ) name that
    depends on a template parameter
  • The default is to assume its not a type
  • If you want a type, use typename
  • typename vectorltTgtiterator it
  • If you dont use typename when you need it, you
    get confusing errors

8
Quotation
  • Computer science is the opposite of biology
  • In biology one seeks to classify things by
    their differences. In computer science one seeks
    to find the similarities.
  • -- Yannis Smaragdakis

9
Goals of good design
  • Maintainable
  • Readable
  • Understandable
  • Flexible
  • I just need you to change one thing
  • Unfortunately
  • School get it to work fast, ignore design

10
(Hopefully) A quick review
  • Object
  • noun
  • encapsulates data
  • with methods that act on it
  • Method
  • verb
  • allows you to ask an object to act on itself
  • vectorltintgt myVector
  • myVector.push_back(7)

11
Other considerations
  • Classes should be re-usable/flexible
  • vectorltTgt hold any type
  • STL lots of templates
  • A class should represent one type of thing
  • Dont use monolithic design
  • (everything in one big class)

12
Slightly humourus story
  • In my undergrad OO design class, on the practice
    test What is wrong with these classes
  • .
  • ProcessMap

13
Speaking of vector..
  • vectorltTgt similar to java vector
  • has overloaded myVect1
  • has push_back() to add to end
  • has pop_back() to remove from end
  • Supports iterators
  • include ltvectorgt
  • google for other functionality

14
Iterator
  • Iterator container position
  • vectorltintgtiterator it myVect.begin()
  • while (it ! myVect.end())
  • int x it
  • cout ltlt Current thing is ltlt x ltlt endl
  • it

iterator type is inside vectorltintgt
15
Many STL classes Iterator
  • listltTgtiterator
  • mapltkey,datagtiterator
  • setltTgtiterator
  • All iterators look the same
  • go to next
  • current item
  • Decouples element access from structure

16
Why iterators?
  • templateltclass itgt
  • int sum (it cur, it last)
  • int sum 0
  • while (cur ! last)
  • sum cur
  • cur
  • Can sum iterators from any containers (of ints)
  • Lists
  • Maps
  • Vectors
  • Your own container?
  • .

17
STL has various algorithms
  • include ltalgorithmgt
  • sort
  • min_element
  • set_union
  • count
  • etc
  • Almost all act on iterators
  • Allows to act on any type of container

18
Design pattern
  • General reusable software concept
  • Just saw Iterator design pattern
  • Canonical book Gang of Four
  • Design Patterns
  • Elements of Reusable Object-Oriented Software
  • Erich Gamma, Richard Helm, Ralph Johnson, and
    John Vlissides

19
Abstract Factory
  • Suppose we are doing something with crypto
  • Different crypto algorithms (RSA, AES, etc)
  • For each algorithm
  • Encrypter class (handles encryption/decryption)
  • KeyGenerator class (to make keys)
  • AESEncrypter/AESKeyGen
  • RSAEncrypter/RSAKeyGen
  • Once we select an algorithm, we want to make
    instances of the proper classes in various places

20
Abstract factory
  • class CryptoFactory
  • virtual Encrypter makeEncrypter() 0
  • virtual KeyGen makeKeyGen() 0
  • class AESFactory public CryptoFactory
  • virtual Encrypter makeEncrypter()
  • return new AESEncrypter()

21
Abstract Factory in use
  • CryptoFactor cf createFactoryFromUserChoice()
  • // which returns new AESFactory()
  • // or new RSAFactory()
  • KeyGen g cf-gtmakeKeyGen()
  • Encrypter e cf-gtmakeEncrypter()
  • //use g and e as appropriate

22
Opposite of biology
  • Remember the quote at the start?
  • Abstract Factory is a great example
  • Decide once what factory to make
  • After just call methods on it to make things
  • Call methods on objects to do things
  • Dynamic dispatch handles all of the decision
    making

23
Decorator Java IO
  • FileInputStream fis new FileInputStream(f)
  • DataInputStream dis new DataInputStream(fis)
  • Sound familiar?
  • Java IO uses the Decorator pattern
  • DIS wraps FIS and decorates it with new
    functionality (in this case readInt() etc).

24
Tons of other design patterns
  • Visitor easy to add new operations to a
    structure
  • Memento restore to previous state
  • Object pool Recycle rather than free/allocate
  • Many many more
  • Good to learn about if you plan to design large
    OO systems

25
Back to vectors..
  • Suppose you want to remove from a vector
  • myVect.remove(x) right?
  • No
  • remove(myVect.begin(), myVect.end(), x)

26
Why?
  • STL algorithms have remove() which works on
    iterators
  • None of the STL containers have a remove
  • Use the remove algorithm instead
  • Good or bad design choice?
  • What do you think?

27
Other STL things map
  • mapltstring,intgt m
  • mabc 24
  • mdef 42
  • cout ltlt abc is ltlt mabc ltlt endl
  • cout ltlt xyz is ltlt mxyz ltlt endl

28
Other STL things map
  • mapltstring,intgt m
  • mabc 24
  • mdef 42
  • cout ltlt abc is ltlt mabc ltlt endl
  • cout ltlt xyz is ltlt mxyz ltlt endl
  • Output
  • abc is 24
  • xyz is 0

29
map returns a
  • Since the returns a reference
  • It cant return NULL
  • So if not found it returns a default object
  • T() for objects
  • 0 for ints
  • etc
  • My opinion terrible choice
  • May seem convenient, but probably leads to bugs

30
A better choice exceptions
  • Recall from Java exceptions indicate erroneous
    conditions
  • For example requested key not found in data
    structure
  • Exceptions are thrown and caught
  • In C any type can be thrown/caught

31
I.e. could throw an int
  • try
  • throw 27
  • catch (int x)
  • cout ltlt Just threw int ltlt x ltlt endl

32
More useful example
  • class myexn public exception
  • virtual const char what() const throw()
  • return Some info about the exception
  • try
  • throw myexn() // create and throw myexn
  • catch (exception e) ..

33
More useful example
  • class myexn public exception
  • virtual const char what() const throw()
  • return Some info about the exception
  • try
  • throw myexn() // create and throw myexn
  • catch (exception e) ..

Like throws in Java specifies what types this
method can throw
34
More useful example
  • class myexn public exception
  • virtual const char what() const throw()
  • return Some info about the exception
  • try
  • throw myexn() // create and throw myexn
  • catch (exception e) ..

Catching by reference allows us to catch subtypes
35
What about resources?
  • void foo(int x)
  • MyObject y(x) //construct on stack
  • .
  • if(error_condition) throw something()
  • What happens to y when something is thrown?

36
Stack unwind destruct
  • When an exception is thrown, C behaves like
    each function returns in order (until a handler
    is found)
  • Called unwinding the stack
  • When each stack frame is destroyed, objects in it
    are destructed
  • y will have the destructor for MyObject run to
    clean it up

37
What about pointers?
  • void foo(int x)
  • MyObject y new MyObject(x)
  • .
  • if (error_condition) throw something()
  • Subtle, but important difference
  • y is now a MyObject pointer on stack
  • object is on heap

38
What about pointers?
  • void foo(int x)
  • MyObject y new MyObject(x)
  • myGlobalList.add(y)
  • if (error_condition) throw something()
  • Maybe we dont even want to delete y
  • Could have added object to something
  • But what if we didnt?

39
auto_ptrltTgt
  • C has an auto_ptrltTgt template
  • Construct pass newed pointer
  • Destruct will delete pointer
  • Copy pointer out will give up ownership
  • Internal pointer NULL, wont delet
  • Can retrieve a copy with get()

40
auto_ptr example
  • auto_ptrltFoogt x (new Foo())
  • auto_ptrltFoogt y
  • y x // x looses ownership (ptr is NULL)
  • y-gtmethod() //call method on the Foo
  • //delete the Foo when y goes out of scope

41
Usefulness
  • auto_ptrs save simplify resource management
  • If auto ptr owns resource when exception thrown
  • Auto ptr gets destructed gt delete memory
  • Use T release() to get raw pointer and disown
  • Use T get() to get raw pointer, not disown (be
    careful)

42
Next week Review
  • Next week review for the exam
  • Questions?
  • Concerns?
  • Confusions?
  • Send me email Ill review whatever you all want
Write a Comment
User Comments (0)
About PowerShow.com